242. Valid Anagram*

242. Valid Anagram*

https://leetcode.com/problems/valid-anagram/

题目描述

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

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true

Example 2:

Input: s = "rat", t = "car"
Output: 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?

C++ 实现 0

20210323 更新: 使用哈希表, 注意最后还要保证哈希表为空.

class Solution {
public:
    bool isAnagram(string s, string t) {
        unordered_map<char, int> record;
        for (auto &c : s) record[c] ++;
        for (auto &c : t) {
            if (!record.count(c)) return false;
            record[c] --;
            if (record[c] == 0) record.erase(c);
        }
        return record.empty();
    }
};

C++ 实现 1

Anagram 应该是说 t 是由 s 中的字符串任意排列形成的. 要判断 t 是否为 s 的 Anagram, 首先要判断它们大小是否相等, 其次判断 t 中的每种字符的个数是否等于 s 中每种字符的个数.

class Solution {
public:
    bool isAnagram(string s, string t) {
        if (s.size() != t.size()) return false;
        unordered_map<char, int> A, B;
        for (auto &c : s) A[c] ++;
        for (auto &c : t) B[c] ++;
        for (auto &p : A) {
            if (!B.count(p.first) || B[p.first] != p.second) return false;
        }
        return true;
    }
};

C++ 实现 2

由于题目中已经说明 st 中只包含小写字母, 那么也可以用数组来表示哈希表.

class Solution {
public:
    bool isAnagram(string s, string t) {
        if (s.size() != t.size()) return false;
        int record[256] = {0};
        for (int i = 0; i < s.size(); ++i) {
            record[s[i]] ++;
            record[t[i]] --;
        }
        for (int i = 0; i < 256; ++i)
            if (record[i] != 0)
                return false;
        return true;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值