242. Valid Anagram

Hash table

1.問題

  • 給予字串s, t, 決定t是否是s的重新排序字

2.想法

  • 紀錄每個字元出現的次數

3.程式碼

class Solution {
public:
    bool isAnagram(string s, string t) {
        int size1 = s.size();
        int size2 = t.size();
        if (size1 == 0 && size2 ==0)
        {
            return true;
        }
        vector<int> cnt1(128, 0);
        vector<int> cnt2(128, 0);
        for (int i = 0; i < size1; i++)
        {
            cnt1[s[i]]++;
        }
        for (int i = 0; i < size2; i++)
        {
            cnt2[t[i]]++;
        }
        for (int i = 0; i < 128; i++)
        {
            if (cnt1[i] != cnt2[i])
            {
                return false;
            }
        }
        return true;
    }
};

4.Performance

Last updated