Java char to entire string compare - java

I have an issue with a string compare problem...
lets say: string a = "0123456789ABCDEF" string b = "00CC0G"
how do i loop a java code so i can check string a for match with each letter from string b. While comparing the match, the letter from string b has to go thru the entire loop against string a before deciding if there is a match or not. if a match is found it should check the next letter in string b against string a and so on until the last letter in string b. if no match is found, the function shud exit the loop and return false. otherwise if each letter in string b is a match atleast once with string a, the function shud return true.
Example... the function should return false, because the first 5 letters match but the last one doesnt.
any idea? Thanks
EDIT: what i have so far
public boolean checkVal(String b) {
// b = "00CC0G";
String a = "0123456789ABCDEF";
String toUC = b.toUpperCase();
char[] cArray = toUC.toCharArray();
char[] vArray = a.toCharArray();
int j = 0;
int m = 0;
for (int i = 0; i <=cArray.length(); i++) {
for (int k = 0; k <= vArray.length(); k++) {
if (cArray[k] == vArray[i]) {
j++;
}
else {
m--;
break; //loop should exit if there is a non match and function should return false
}
}
}
if (j > 0) return true; //string a matched atleast once with string b
if (m < 0) return false; //string a alteast has one NO MATCH with string b
}
The looping is what getting me confused...

Spoonfeeding since 2k12.
public static boolean isValid(String a, String b){
for(char c : b.toCharArray())
if(!a.contains(""+c))
return false;
return true;
}

Related

How to check for palindrome excluding the non-alphanumeric characters?

Here's the code that I attempted
public String isPalindrome(String s) {
String trimmed = s.replaceAll("[^A-Za-z0-9]", "");
String reversed = "";
int len = trimmed.length();
for (int i = len - 1; i >= 0; i--) {
char[] allChars = trimmed.toCharArray();
reversed += allChars[i];
}
if (trimmed.equalsIgnoreCase(reversed)) {
return "true";
} else {
return "false";
}
}
Sample Input 1
A man, a plan, a canal: Panama
Sample Output 1
true
Explanation 1
The given string is palindrome when considering only alphanumeric characters.
Sample Input 2
race a car
Sample Output 2
false
Explanation 2
The given string is not a palindrome when considering alphanumeric characters.
Your variable len comes from the length of the String s. But you use the value on the array coming from trimmed.
So if you want to remove the IndexOutOfBoundsException you should change your len declaration to:
int len = trimmed.length();
You can return boolean instead of String:
public static boolean isPalindrome(String s) {
String trimmed = s.replaceAll("[^A-Za-z0-9]", "").toLowerCase();
int from = 0, to = trimmed.length() - 1;
while (from < to) {
if (trimmed.charAt(from) != trimmed.charAt(to)) {
return false;
}
from++;
to--;
}
return true;
}
You can use StringBuilder to reverse a String:
public static void main(String[] args) {
String input = "a#b!b^a";
String clean = input.replaceAll("[^A-Za-z0-9]", "");
String reverse = new StringBuilder(clean).reverse().toString();
boolean isPalindrome = reverse.equals(clean);
System.out.println(isPalindrome);
}
You can do like this in linear time as the loops are driven by the presence of non-alphabetic/digit characters. Also, no trimming or reversal of the string is required.
String[] test = {"A man, a plan, a canal: Panama",
"race a car","foobar", "ABC2CEc2cba"};
for (String s : test) {
System.out.printf("%5b -> %s%n", isPalindrome(s), s);
}
prints
true -> A man, a plan, a canal: Panama
false -> race a car
false -> foobar
true -> ABC2CEc2cba
The outer while loop drives then entire process until the indices cross or are equal. The inner loops simply skip over non-alphabetic/digit characters.
public static boolean isPalindrome(String s) {
int k = s.length() - 1;
int i = 0;
char c1 = '#';
char c2 = '#';
while (i <= k) {
while (!Character.isLetterOrDigit(c1 = s.charAt(i++)));
while (!Character.isLetterOrDigit(c2 = s.charAt(k--)));
if (Character.toLowerCase(c1) != Character.toLowerCase(c2)) {
return false;
}
}
return true;
}

How to check that one String can be spelled using characters from another String?

Example: String a = "ACAHBBA" and String b = "ABAB" should return true, since both strings can spell ABAB.
I have tried with contains(), but that only works for equal sequences.
// The code should look like this.
public class task10 {
public static boolean contains(String a, String b) {
// check if b can be spelled using characters from a.
// if it can. return true.
// else
return false;
}
}
Posible solution?
public static boolean contains(String a, String b) {
for (int i = 0; i < b.length(); i++) {
if (a.indexOf(b.charAt(i)) == -1) {
return false;
}
}
return true;
}
Simply iterate thru one string and get the index of the character. If >= 0, replace character with non-alphabetic character and repeat. This algorithm presumes the need to match the correct number of characters. For example, hello would return false if the character set was helo.
public static boolean spelledFrom(String word, String chars) {
StringBuilder sb = new StringBuilder(chars);
for (String c : word.split("")) {
int i;
if ((i = sb.indexOf(c)) < 0) {
return false;
}
sb.setCharAt(i, '#');
}
return true;
}
You can try this:
public static boolean canSpell(String a, String b)
{
String shorter = (a.length() <= b.length()) ? a : b;
String longer = (shorter.equals(a)) ? b : a;
for(int i = 0; i < shorter.length(); i++)
{
if(!longer.contains("" + shorter.charAt(i)))
return false;
}
return true;
}
Once you've identified the shorter string, you just need to verify that each of its chars are contained in the longer string. This solution doesn't verify if a char "has already been used", which means inserting "AB" and "ABBA" will return true. If you need to do this, you just need to delete the verified char from the longer string in every loop.

LeetCode 14. longest common prefix

Question:
Write a function to find the longest common prefix string among an array of strings. If there is no common prefix, return an empty string "".
Example 1:
Input: ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Code:
public class Solution {
public String longestCommonPrefix(String[] strs) {
if(strs==null || strs.length==0)
return "";
for(int i=0;i<strs[0].length();i++) {
char x = strs[0].charAt(i);
for(int j=0;j<strs.length;j++) {
if((strs[j].length()==i)||(strs[j].charAt(i)!=x)) {
return strs[0].substring(0,i);
}
}
}
return strs[0];
}
}
This is the second solution, but I don't understand the inner loop.
I think if the second element in strs returns a string and ends the for loop, the third element will not have a chance to be compared.
You have to check same position in all of the words and just compare it.
positions
word 0 1 2 3 4 5
=====================
w[0] F L O W E R
w[1] F L O W
w[2] F L I G H T
In Java:
class Main {
public static void main(String[] args) {
String[] words = {"dog","racecar","car"};
String prefix = commonPrefix(words);
System.out.println(prefix);
// return empty string
String[] words2 = {"dog","racecar","car"};
String prefix2 = commonPrefix(words2);
System.out.println(prefix2);
// Return "fl" (2 letters)
}
private static String commonPrefix(String[] words) {
// Common letter counter
int counter = 0;
external:
for (int i = 0; i < words[0].length(); i++) {
// Get letter from first word
char letter = words[0].charAt(i);
// Check rest of the words on that same positions
for (int j = 1; j < words.length; j++) {
// Break when word is shorter or letter is different
if (words[j].length() <= i || letter != words[j].charAt(i)) {
break external;
}
}
// Increase counter, because all of words
// has the same letter (e.g. "E") on the same position (e.g. position "5")
counter++;
}
// Return proper substring
return words[0].substring(0, counter);
}
}
Your first loop is itterating over all chars in the first string of array. Second loop is checking char at i posistion of all strings of array. If characters do not match, or length of string is the same as i it returns substring result.
I think the best way to understand is debug this example.
If the char in the second string is different than the char in the first one, then it is correct to return, since it means that the common prefix ends there. Checking the third and following strings is not necessary.
Basically it returns as soon as it finds a mismatch char.
If we first sort them then it would be very easy we have to only go and compare the first and the last element in the vector present there so,
the code would be like,This is C++ code for the implementation.
class Solution {
public:
string longestCommonPrefix(vector<string>& str) {
int n = str.size();
if(n==0) return "";
string ans = "";
sort(begin(str), end(str));
string a = str[0];
string b = str[n-1];
for(int i=0; i<a.size(); i++){
if(a[i]==b[i]){
ans = ans + a[i];
}
else{
break;
}
}
return ans;
}
};
public class Solution {
public string LongestCommonPrefix(string[] strs) {
if(strs.Length == 0)
{
return string.Empty;
}
var prefix = strs[0];
for(int i=1; i<strs.Length; i++) //always start from 1.index
{
while(!strs[i].StartsWith(prefix))
{
prefix = prefix.Substring(0, prefix.Length-1);
}
}
return prefix;
}
}

How to read specific special character

I have a string like
Str s1 = abd,jh
Str2 = aa$$ab
I want to read string which have only a,b and $.
Str1 return false
Str2 return true.
My Code
public static boolean containsOtherCharacter(String str) {
String[] st = str.split("");
for(int x = 0; x < st.length; x++)
if (st[x].compareTo("A") != 0 && st[x].compareTo("B") != 0 && st[x].compareTo("$") != 0)
return true;
return false;
}
Any help how to read that. Any other value other then this should be ignored.
You're trying to overcomplicate things here. You could simply use a regular expression, like
String s = "aa$$ab";
System.out.println(s.replaceAll("[ab$]", "").length()==0);
It removes a, $, and b from the String. After that, if the length is greater than 0, then the String must have had some other characters.Note that it is case sensitive.
public static boolean hasSpecialChar( String input)
{
boolean found = true;
int len = input.length();
for(int i = 0; i< len ; i++)
{
if(input.charAt(i)== 97|| input.charAt(i)==98 ||input.charAt(i)==36)
{
// read the string
}
else
{
found = false;
return found;
// give out the error
}
}
return found ;
}
As you want to only read the a, b and $ thus we could use the ASCII values of the character and thus read in the string or line character by character and check the input. As the ASCII values for a is equal to 97, 98 for b and 36 for $ this would work fine for this case.
Hope is helps you!!! #shanky singh
Here's another way to solve this:
public static boolean containsOtherCharacter(String str) {
boolean The_answer=false;
int count0 = StringUtils.countMatches(str, "a");
int count1 = StringUtils.countMatches(str, "b");
int count2 = StringUtils.countMatches(str, "$");
int ans=count0+count1+count2;
if(ans==str.length())The_anser=true;
return The_answer;
}

Java: How to remove all occurrences of a set of letters stored as a string from another string?

I am trying to figure out how to write a method that will remove letters in a
string based on another string. The method would end up like so:
removeLetter("file", "fe")
The only thing that should be returned is the string "il". So far I have something like this:
public class h
{
public static void main(String[] args)
{
String a="file";
String b="fe";
char letter;
int i;
int j;
for (letter = 'a'; letter <= 'z'; letter++)
{
for (i=0; i < a.length()-1; i++)
{
for (j=0; j < b.length()-1; j++) // This is the loop i get stuck on
{
char r = b.charAt(j);
char s = a.charAt(i);
if ( letter == r && letter == s);
System.out.print(r + " " + s);
}
}
}
}
}
I know the bottom part is wrong but I am not sure where to go from here.
You can do this with a regular expression:
a.replaceAll("[" + b + "]", "")
This works by constructing a character class like [fe], and replacing characters which match that with the empty string.
Of course, this is a bit of a hack, in that you can easily choose b such that it won't yield a valid regular expression. However, if you know that b will only ever contain letters, this would work.
Here's a pretty simple nested array using a flag boolean :
public static void main(String[] args) {
String a = "file";
String b = "f";
String c = "";
StringBuilder sb = new StringBuilder();
boolean contains;
for (int i = 0 ; i < a.length() ; i++){
contains = false;
for (int j = 0 ; j < b.length() ; j++){
if (a.charAt(i) == b.charAt(j)) contains = true;
}
if (!contains) sb.append(a.charAt(i));
}
System.out.println(sb);
}
It checks every char of the first word with the chars of the second and changes the flag to true if the char is contained in both.
If it is not the case, the char of the first word is added to the new String, if the contrary, nothing happens and we continue to the next char of the first String.
Let's remove all the vowels of this word : Supercalifragilisticexpialidocious
String a = "Supercalifragilisticexpialidocious";
String b = "aeiou";
Here's the output :
Sprclfrglstcxpldcs

Categories