Saturday, September 23, 2017

242. Valid Anagram

Given two strings s and t, write a function to determine if t is an anagram of s.
For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.
Note:
You may assume the string contains only lowercase alphabets.
Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?

Solution
Since both string only contains lowercase alphabets, we can use an array with length of 26 to keep tracking the counts of all letters. 
We update the count for both s and t at one iteration and check the counter array there after if any letter has counter that is not 0, it means s and t are not anagram.
Or we can increment counter for s first then decrement counter for t, if anytime any letter has counter less than 0, it means s and t are not anagram.

To the follow up question, we can use a hashmap to track the counters if strings contain unicode characters.
public boolean isAnagram(String s, String t) {  
     if(s==null) return t==null;  
     if(t==null) return s==null;  
     if(s.length()!=t.length()) return false;  
     int[] count=new int[26];  
     for(int i=0;i<s.length();i++){  
       count[s.charAt(i)-'a']++;  
       count[t.charAt(i)-'a']--;  
     }  
     for(int i=0;i<26;i++){  
       if(count[i]!=0) return false;  
     }  
     return true;  
   }  
 public boolean isAnagram(String s, String t) {  
     if(s==null) return t==null;  
     if(t==null) return s==null;  
     if(s.length()!=t.length()) return false;  
     int[] map=new int[26];  
     for(int i=0;i<s.length();i++){  
       map[s.charAt(i)-'a']++;  
     }  
     for(int i=0;i<t.length();i++){  
       map[t.charAt(i)-'a']--;  
       if(map[t.charAt(i)-'a']<0) return false;  
     }  
     return true;  
   }  

No comments:

Post a Comment