Leetcode 有效的字母异位词

本文最后更新于:2022年3月23日 晚上

地址:https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/5/strings/35/

题目

给定两个字符串 st ,编写一个函数来判断 t 是否是 s 的一个字母异位词。

示例 1:

输入: s = "anagram", t = "nagaram"
输出: true

示例 2:

输入: s = "rat", t = "car"
输出: false

说明:
你可以假设字符串只包含小写字母。

进阶:
如果输入字符串包含 unicode 字符怎么办?你能否调整你的解法来应对这种情况?

我的解决方案

class Solution {
public:
    bool isAnagram(string s, string t) {
        bool bl = true;   //作为返回值,初始化为true
        int sc[26];   //sc[],tc[]用于记录字符串中各个字符的个数
        int tc[26];
        for (int i = 0; i < 26; i++) {   //初始化sc[],tc[]为全0
            sc[i] = 0;
            tc[i] = 0;
        }
        if (s.size() != t.size())   //字符串大小不等显然不是有效的字母异位词
            bl = false;
        else {    //字符串大小相等的情况
            for (int i = 0; i < s.size(); i++) {
                int saddr = s[i] - 97;    //转换字符s[i]作为数组sc[]的下标
                int taddr = t[i] - 97;    //同上
                sc[saddr]++;   //统计以saddr为下标代表的字符在字符串s中出现的次数
                tc[taddr]++;   //同上
            }
            for (int j = 0; j < 26; j++) {   //判断是否有效的字母异位词
                if (sc[j] != tc[j]) {   //若某个字母在两字符串中的个数不相等,说明不是有效的字母异位词
                    bl = false;
                    break;
                }
            }
        }
        return bl;
    }
};

Leetcode 有效的字母异位词
https://mxy493.xyz/201902029846/
作者
mxy
发布于
2019年2月2日
许可协议