I noticed a few different problems with your code. One small problem is you break if the length
s are not the same, but
if(count==l1 && count==l2){
return true;
}
still checks if they both equal. One of those can be removed as it will always be true.
Another problem I have found is that if you put the break
in the loops to check for more than one occurrence of a character, but if you hand trace it, it is not actually doing this.
Let's go over the loops.
You are taking one character from c1
and checking it against all characters from c2
. If they match, you add one to count and break out of the c2
loop and get the next char of c1
. Then you start over.
It sounds like a good plan, except that you start at the beginning of c2
again. So if c1
has multiple characters, it only recognizes the first character in c2
as matching. This will give you problems later on. Changing your input to "aabcd" "acgdb"
will fool your logic.
I did it a different way, utilizing a HashMap
and a ternary operator. Using a HashMap
like this will help you in the long run, as it maps a char
to an int
, in this case one character and the amount of them. Doing this for each input will give you two maps, either identical or not.
public static void main(String[]args){
//Diff lengths = false
System.out.println(check("acd", "bacd"));
//Same letters, mixed = true
System.out.println(check("abcd", "bacd"));
//Same string = true
System.out.println(check("abcd", "abcd"));
//Diff letters = false
System.out.println(check("abcd", "gacd"));
//Same characters = true
System.out.println(check("abcd123$", "1b2a3c$d"));
//Multiple occurances of a letter = true
System.out.println(check("aaacddbg", "acadadgb"));
}
public static boolean check(String c1, String c2){
if(c1.length() != c2.length()){
return false;
}
char[] word1 = c1.toCharArray();
char[] word2 = c2.toCharArray();
Map<Character, Integer> map1 = new HashMap<>();
Map<Character, Integer> map2 = new HashMap<>();
for(int i = 0; i < word1.length; i++){
map1.put(word1[i], (map1.get(word1[i]) == null) ? 1 : map1.get(word1[i])+1);
}
for(int i = 0; i < word2.length; i++){
map2.put(word2[i], (map2.get(word2[i]) == null) ? 1 : map2.get(word2[i])+1);
}
if(map1.equals(map2)){
return true;
}else{
return false;
}
}