242. Valid Anagram

来源:互联网 发布:淘宝开网店用18 编辑:程序博客网 时间:2024/06/05 16:12

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?

s思路:
1. 区别一下anagram是字母一样,但顺序不同;parlindrome是回文。容易搞混。
2. 由于只有lowercase.因此,用26长的vector来存出现的次数,等效于hash。
3. 经常需要用数组代替hash,只要元素个数已知,且是数字!

//方法1:用数组代替hashtableclass Solution {public:    bool isAnagram(string s, string t) {        //        if(s.size()!=t.size()) return false;        vector<int> v(26,0);        for(char c:s){            v[c-'a']++;        }        for(char c:t){            if(v[c-'a']--==0) return false;          }        return true;    }};
0 0