You can create an int array that will keep count of each character see in the first string. Then iterate through each character seen in the second string. If at the end, the int array contains zero count for each character, then that means string 1 and string 2 both contains the same occurrence of each character and thus, they are anagrams!
public class HelloWorld
{
public static boolean anagram(String first, String second)
{
// if the lengths of both strings are not the same, then they cannot
// be anagrams
if (first.length() != second.length())
return false;
// int array to keep count of each character
int[] letters = new int[256];
// increment the count of each character in the first string
// that we see
for (char c : first.toCharArray())
{
letters[c]++;
}
// decrement the count of each character we see in the second
// string
for (char character : second.toCharArray())
{
letters[character]--;
}
// check to see that each character count is zero and if so,
// that means the occurrence of each letter in both strings
// are the same, and hence they are anagrams, return false
// if we find a letter count that is not 0
for (int i : letters)
{
if (letters[i] != 0)
return false;
}
return true;
}
public static void main(String []args){
System.out.println(anagram("bob", "bbo"));
}
}
No comments:
Post a Comment