Saturday, August 1, 2015

LeetCode [242] Valid Anagram

 242. Valid Anagram

Easy

Given two strings s and , write a function to determine if t is an anagram of s.

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true

Example 2:

Input: s = "rat", t = "car"
Output: 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?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
public:
    bool isAnagram(string s, string t) {
        if((int)s.size()!=(int)t.size()) return false;
        int hash[26] = {0};
        for(int i=0; i<(int)s.size(); ++i){
            hash[s[i]-'a']++;
            hash[t[i]-'a']--;
        }
        for(int i=0; i<26; ++i){
            if(hash[i]) return false;
        }
        return true;
    }
};

1
2
3
4
5
6
7
8
class Solution {
public:
    bool isAnagram(string s, string t) {
        sort(s.begin(), s.end());
        sort(t.begin(), t.end());
        return s==t;
    }
};

No comments:

Post a Comment