[leetcode] 242. Valid Anagram 解题报告

题目链接:https://leetcode.com/problems/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?


思路:用一个hash表来记录每一个字符出现的次数,一个字符串使hash表增加,一个字符串使hash表减少,最后看hash表值是不是为0.

如果包含unicode我觉得应该是两位作为一个子串来做hash。

代码如下:

class Solution {
public:
    bool isAnagram(string s, string t) {
        if(s.size() != t.size())
            return false;
        int hash[26];
        memset(hash, 0, sizeof(hash));
        for(int i = 0; i< s.size(); i++)
            hash[s[i]-'a']++;
        for(int i = 0; i< t.size(); i++)
            hash[t[i]-'a']--;
        for(int i = 0; i< 26; i++)
            if(hash[i] != 0)
                return false;
        return true;
    }
};


你可能感兴趣的:(LeetCode,算法,hash)