[LeetCode]242. Valid Anagram

来源:互联网 发布:淘宝助理ipad版 编辑:程序博客网 时间:2024/05/01 20:17

[LeetCode]242. Valid Anagram

题目描述

这里写图片描述

思路

1 hash map 对s中计数加,对t中计数减,结果不为0或者不存在的直接返回false
2 sort 直接排序后 返回 s == t ,效率最低
3 array, 初始化一个长度为26,值为0的数组,对字符串同时遍历,最后检查数组元素,有不为0的元素直接返回false

代码

#include<iostream>#include<string>#include<vector>#include<unordered_map>#include<algorithm>using namespace std;class Solution {public:    bool isAnagram(string s, string t) {        /*        // unordered map        if (s.size() > t.size())            swap(s, t);        unordered_map<char, int> m;        for (char ch : s)            ++m[ch];        for (char ch : t) {            if (m.count(ch) && m[ch] > 0) {                --m[ch];            }            else {                return false;            }        }        return true;        */        /*        //sort        sort(s.begin(), s.end());        sort(t.begin(), t.end());        return s == t;        */        //array        if (s.size() != t.size())            return false;        vector<int> counts(26, 0);        for (int i = 0; i < s.size(); ++i) {            counts[s[i] - 'a'] ++;            counts[t[i] - 'a'] --;        }        for (int i = 0; i < 26; ++i)            if (counts[i])                return false;        return true;    }};int main() {    Solution s;    cout << s.isAnagram("ab", "a") << endl;    system("pause");}
0 0
原创粉丝点击