leetcode 242. Valid Anagram

题目描述

因为s和t仅仅包含小写字母,所以可以开一个26个元素的数组用来做哈希表。不过如果是unicode字符,那就用编程语言自带的哈希表。

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

用unordered_map

class Solution {
public:
    bool isAnagram(string s, string t) {
        int n = s.size();
        if(s.size() != t.size())
            return false;
        unordered_map<char,int> hash_table;
        for(char ch:s){
            if(hash_table.contains(ch)){
                hash_table[ch]++;
            }else{
                hash_table[ch] = 1;
            }
        }

        for(char ch:t){
            if(hash_table.contains(ch)){
                n--;
                hash_table[ch]--;
                if(hash_table[ch] == 0)
                    hash_table.erase(ch);
            }else{
                return false;
            }
        }
        return n==0;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值