Skip to content
本页目录

0242-有效的字母异位词

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

给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。 注意:若s 和 t中每个字符出现的次数都相同,则称s 和 t互为字母异位词。

示例1:

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

示例 2:

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

提示:

1 <= s.length, t.length <= 5 * 104
s 和 t仅包含小写字母

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

思路

使用字典,循环第一个字符串,将char加入字典,同样的char增加计数 循环第二个字符串,取出字典中的数据,如果发现没有,则返回false 注意题目要求 异位词 必须两边的字母数量相等,所以最后需要检测dict

关于进阶问题: 进阶问题的核心点在于「字符是离散未知的」,因此我们用哈希表维护对应字符的频次即可。同时读者需要注意 Unicode 一个字符可能对应多个字节的问题,不同语言对于字符串读取处理的方式是不同的。

csharp
public class Solution {
    public bool IsAnagram(string s, string t) {
    	Dictionary<char,int> dict = new Dictionary<char,int>();
    	for(int i=0; i < s.Length; i++){
    		if(dict.ContainsKey(s[i])){
    			dict[s[i]]++;
    		}
    		else{
    			dict.Add(s[i],1);
    		}
    	}
    	for(int i=0; i < t.Length; i++){
    		if(dict.ContainsKey(t[i]) && dict[t[i]] > 0){
    			dict[t[i]]--;
    		}
    		else{
    			return false;
    		}
    	}
        //检测字典中所有的字母应该都被取走
    	foreach(char key in dict.Keys){
    		if(dict[key] > 0){
    			return false;
    		}
    	}
    	return true;
    }
}

思路2:排序后字符串应该相等

csharp
public class Solution {
    public bool IsAnagram(string s, string t) {
        if(s.Length != t.Length){
            return false;
        }
        //排序
        char[] arrS = s.ToCharArray();
        char[] arrT = t.ToCharArray();
        Array.Sort(arrS);
        Array.Sort(arrT);
        for(int i=0; i<arrS.Length; i++){
            if(arrS[i] != arrT[i]){
                return false;
            }
        }
        return true;
    }
}

Released under the MIT License.