Monday, July 4, 2016

Valid Anagrams

Problem:
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:
class Solution {
public:
    bool isAnagram(string s, string t) {
        if (s.empty() && t.empty())
            return true;
        sort(s.begin(), s.end());
        sort(t.begin(), t.end());
        return s == t;
    }
};

Another one:
  1. class Solution {  
  2. public:  
  3.     bool isAnagram(string s, string t) {  
  4.         int len1 = s.length();  
  5.         int len2 = t.length();  
  6.         if(len1!=len2){  
  7.             return false;  
  8.         }  
  9.         vector<int> count(26, 0);  
  10.         for(int i=0; i<len1; i++){  
  11.             count[s[i]-'a']++;  
  12.         }  
  13.         for(int i=0; i<len2; i++){  
  14.             if(--count[t[i]-'a']<0){  
  15.                 return false;  
  16.             }  
  17.         }  
  18.         return true;  
  19.     }  
  20. };  


======= Another one =====

class Solution {
public:
    bool isAnagram(string s, string t) {
        if (s.size() != t.size()) {
            return false;
        }
        unordered_map<char, int> mp;
       
        for (auto ch: s) {
            mp[ch]++;
        }
       
        for (auto ch: t) {
            if (!mp.count(ch)) {
                return false;
            }
            mp[ch]--;
            if (mp[ch] < 0) {
                return false;
            }
        }
       
        return true;
    }
};

No comments:

Post a Comment