LeetCode Valid Anagram

LeetCode Valid Anagram

题目

Given two strings s and t, write a function to determine if t is an
anagram of s.

For example, s = “anagram”, t = “nagaram”, return true. s = “rat”, t =
“car”, return false.

Note: You may assume the string contains only lowercase alphabets.

Follow up: What if the inputs contain unicode characters? How would
you adapt your solution to such case?

Subscribe to see which companies asked this question

思路&代码

对于只有小写字母的情况,只需要开一个26个int大小的数组对两个字符串进行字母统计即可,对一个字符串加而对另一个字符串减。这样,如果最后统计数组有一个字符次数不为0,即可知道不一样。

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

但是,如果字符有可能包含Unicode字符,也就是有65536个字符的情况下,当然我们思路也是一样,也可以使用数组来统计。但是这样就会造成极大的空间浪费,所以我选择牺牲时间而节约空间使用map来统计,时间上大概增加了100ms(仅在此题中)。

class Solution {
public:
    bool isAnagram(string s, string t) {
        map<char, int> hash;
        for (int i = s.size() - 1; i >= 0; i--) {
            if (hash.find(s[i]) == hash.end()) hash[s[i]] = 1;
            else hash[s[i]]++;
        }
        for (int i = t.size() - 1; i >= 0; i--) {
            if (hash.find(t[i]) == hash.end()) return false;
            else hash[t[i]]--;
        }
        for (map<char, int>::iterator iter = hash.begin(); iter != hash.end(); iter++) 
            if (iter->second != 0) return false;
        return true;
    } 
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值