Eagle233-Blog

[Algorithms] LeetCode 242. 有效的字母异位词


Categories Algorithms HashTable
Tags

163 Words   |   1 Minutes

来源:代码随想录

LeetCode 242. 有效的字母异位词

数组作为哈希表

class Solution {
public:
    bool isAnagram(string s, string t) {
        vector<int> a(26, 0);
        for (int i = 0; i < s.size(); i++) {
            a[s[i] - 'a']++;
        }

        vector<int> b(26, 0);
        for (int i = 0; i < t.size(); i++) {
            b[t[i] - 'a']++;
        }

        if (a == b) {
            return true;
        }
        return false;
    }
};

也可以不使用vector的==。

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

        for (int i = 0; i < 26; i++) {
            if (a[i] != 0) {
                return false;
            }
        }

        return true;
    }
};


Page views: Loading...  ·  Visitors: Loading...
Except where otherwise noted, original content on this site is dedicated to the public domain under CC0 1.0.
Powered by Hexo & Theme mdsuper
沪ICP备2026040813号
Search