[LeetCode]242. Valid Anagram

[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");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值