[Leetcode] Valid Anagram, Solution

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.
[Thoughts]
对于字符出现次数做个统计就好了。因为只有26个小写字母,所以可以建立一个大小为26的索引数组charcount,用来统计每个字符的出现次数。
对于s, 将其作为字符数组进行遍历,在遍历的过程中,对每个出现的字符计数加一。
对于t, 同样将其遍历,对每个出现的字符计数减一。
如果s和t是anagram , 那么最后的charcount数组中所有字符的计数都应该是0, 否则就不是anagram。

[Code]
1:  class Solution {  
2: public:
3: bool isAnagram(string s, string t) {
4: vector<int> charcount(26, 0);
5: for(int i =0; i< s.length(); i++) {
6: charcount[s[i] - 'a'] ++;
7: }
8: for(int i =0; i< t.length(); i++) {
9: charcount[t[i] - 'a'] --;
10: }
11: for(int i =0; i<charcount.size(); i++) {
12: if(charcount[i] != 0) {
13: return false;
14: }
15: }
16: return true;
17: }
18: };
原文地址:https://www.cnblogs.com/codingtmd/p/5078834.html