I want to return true if string t is an anagram of s. I have pushed all characters of s in the stack and comparing each character of t with the top element in the stack, if the character matches, i perform the pop operation. If at the end, stack is empty, this means the string t is an anagram of string s. Here is my code -
public boolean isAnagram(String s, String t) {
char[] charArray1 = s.toCharArray();
char[] charArray2 = t.toCharArray();
if (s.length() != t.length())
{
return false;
}
Stack<Character> newStack = new Stack<Character>();
for (int i=0; i<charArray1.length;i++)
{
newStack.push(charArray1[i]);
}
for (int j=0;j<charArray2.length;j++)
{
if(charArray2[j] == newStack.peek())
{
newStack.pop();
}
}
if (newStack.isEmpty())
{
return true;
}
else
return false;
}
error: s= "abc", t= "bac", Doesn't seem to declare these two strings as anagram
A stack is the wrong data structure for this problem, because peek()
only looks at the top element of the stack, but you want to check if each character in charArray2
can be found anywhere in charArray1
. A simpler approach is to sort the arrays and then compare them as Strings
:
public boolean isAnagram(String s, String t) {
char[] charArray1 = s.toCharArray();
char[] charArray2 = t.toCharArray();
Arrays.sort(charArray1);
Arrays.sort(charArray2);
String string1 = new String(charArray1);
String string2 = new String(charArray2);
return string1.contentEquals(string2);
}