【LeetCode】242. 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.

提示:

注意题目里提示了两个输入字符串中的字符均为小写字符,因此我们可以建立一个大小为26的字典(数组),其中的对应关系为{0:a, 1:b, ..., 25:z}。用它保存每一个字母出现的次数。

对s,将对应的数字+1,而对于t,将对应的数字-1。最后考察字典的所有元素是否都为零即可判断出每个字符出现的次数是否一致。

代码:

class Solution {
public:
    bool isAnagram(string s, string t) {
        if (s.size() != t.size()) return false;
        int dic[26] = {0};
        for (int i = 0; i < s.size(); ++i) {
            dic[s[i] - 'a']++;
        }
        for (int i = 0; i < t.size(); ++i) {
            dic[t[i] - 'a']--;
        }
        for (int i = 0; i < 26; ++i) {
            if (dic[i] != 0) return false;
        }
        return true;
    }
};
原文地址:https://www.cnblogs.com/jdneo/p/4746078.html