Tuesday 8 December 2015

Anagram


An anagram is a type of wordplay, the result of rearranging the letters of a word or phrase to produce a new word or phrase, using all the original letters exactly once.

Example is "silent" which can be rearranged to "listen"

Question arises to find out whether two given strings are Anagram or not??

There can be multiple ways of solving the problems and most optimal solution would be using least time complexity and space. O(1) is the best and  denotes constant  time complexity , O(n) can be better etc..

Couple of solution is given as follows : 

**
 * @author sachin
 *
 */
public class Anagram {
public static void main(String[] args) {
String firstString = "silent";
String secondString = "listen";
System.out.println(isAnagram1(firstString, secondString));
System.out.println(isAnagram2(firstString, secondString));
//isAnagram1()  method gives solution in time complexity of O(nlogn)
//isAnagram2()  method gives solution in time complexity of O(n)
     
}
public static boolean isAnagram1(String s1, String s2) {
if (s1 == null || s2 == null )
return false;
int len = s1.length();
if (len != s2.length() || len < 2)
return false;
char[] s1CharArr = s1.toLowerCase().toCharArray();
char[] s2CharArr = s2.toLowerCase().toCharArray();
Arrays.sort(s1CharArr);
Arrays.sort(s2CharArr);
return new String(s1CharArr).equals(new String(s2CharArr));

}
public static boolean isAnagram2(String s1, String s2) {
if (s1 == null || s2 == null )
return false;
int len = s1.length();
if (len != s2.length() || len < 2)
return false;

final int LETTERS_LEN = 256;
int[] letters = new int[LETTERS_LEN];

for (int i = 0; i < len; i++) {
letters[s1.charAt(i)]++;//incrementing the character count
letters[s2.charAt(i)]--;//decrementing the character count
}
for (int i = 0; i < LETTERS_LEN; i++) {
if (letters[i] != 0) {
return false; //returning from first non zero element finding means count mismatch
}
}
return true;
}
}

Output : 

true
true
                 

No comments:

Post a Comment