I would like to make anagram algorithm but This code doesn't work. Where is my fault ? For example des and sed is anagram but output is not anagram Meanwhile I have to use string method. not array. :)
public static boolean isAnagram(String s1 , String s2)
{
String delStr="";
String newStr="";
for(int i=0;i<s1.length();i++)
{
for(int j=0 ; j < s2.length() ; j++)
{
if(s1.charAt(i)==s2.charAt(j))
{
delStr=s1.substring(i,i+1);
newStr=s2.replace(delStr,"");
}
}
}
if(newStr.equals(""))
return true;
else
return false;
}
An easier way might be to just sort the chars in both strings, and compare whether they are equal:
public static boolean isAnagram(String s1, String s2){
// Early termination check, if strings are of unequal lengths,
// then they cannot be anagrams
if ( s1.length() != s2.length() ) {
return false;
}
s1=s1.toLowerCase();
s2=s2.toLowerCase();
char[] c1 = s1.toCharArray();
char[] c2 = s2.toCharArray();
Arrays.sort(c1);
Arrays.sort(c2);
String sc1 = new String(c1);
String sc2 = new String(c2);
return sc1.equals(sc2);
}
Personally I think it's more readable than nested for-loops =p
This has O(n log n) run-time complexity, where n
is the length of the longer string.
Edit: this is not the optimal solution. See @aam1r's answer for the most efficient approach (i.e. what you should actually say in an interview)