# Need help on my code...

• Hello guys,

I really need help on debugging this piece of code. the answer was always wrong, I dont know why...Thank you very much!

``````public class Solution {
public boolean isAnagram(String s, String t) {
char[] schar = s.toCharArray();
char[] tchar = t.toCharArray();
Arrays.sort(schar);
Arrays.sort(tchar);
while (schar.length == tchar.length)
{
for (int i=0; i<schar.length; i++)
{
if (schar[i] == tchar[i])
{
return true;
}
else return false;
}
}
return false;
}
}
``````

• @zsyx Here is your solution fixed just now.

``````public class Solution {
public boolean isAnagram(String s, String t) {
char[] schar = s.toCharArray();
char[] tchar = t.toCharArray();
if (schar.length != tchar.length) return false;
Arrays.sort(schar);
Arrays.sort(tchar);
for (int i=0; i<schar.length; i++)
if (schar[i] != tchar[i])
return false;
return true;
}
}
``````

Actually you can handle it as follows in, a C++ solution.

``````class Solution {
public:
bool isAnagram(string s, string t) {
int counts[26]{0};
for(int i = 0; i < s.length(); ++i) counts[s[i]-'a']++;
for(int i = 0; i < t.length(); ++i) counts[t[i]-'a']--;
for(int i = 0; i < 26; ++i) if(counts[i]) return false;
return true;
}
};
``````

• @LHearen Thank you so much!!!

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.