I need to compare 2 strings and see if the number of every character each of them contain is the same.
Requirement:
Without using any packages or imports
My idea:
I want to check if a char from charsA exists within charsB. And if it does, I'll remove it from charsB.
And if the length of charsB is 0 by the end of the for loop, then I know it is an anagram
Issue:
It might end up deleting each character that matches a particular character more than once.
For example, if input is "oellh" and "heloo" (result should be false):
- checks for
o: newcharsB:"hel" - checks for
e: newcharsB:"hl" - checks for
l: newcharsB:"h" - checks for
l: newcharsB:"h" - checks for
h: newcharsB:""
My code:
static boolean isAnagram(String a, String b) {
boolean isAnagram;
//case 2:
//if strings lengths dont match isAnagram is set to false
if(a.length() != b.length()){isAnagram = false;}
// will turn each string into an array or characters
String[] charsA = a.split("");
String[] charsB = b.split("");
for (int i = 0; i < a.length(); i++) {
// some code to compare the strings here.
}
return isAnagram;
}
Test cases
*Input:
"hello", "olhel" // case one
"helloq", "olhel" // case two
"helloq", "olheln" // case three
Output:
true // case one
false // case two
false // case three