【初级算法】15. 有效的字母异位词

题目:

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

例如,
s = "anagram",t = "nagaram",返回 true
s = "rat",t = "car",返回 false

注意:
假定字符串只包含小写字母。

提升难度:
输入的字符串包含 unicode 字符怎么办?你能能否调整你的解法来适应这种情况?

1,解题思路:

本题比较简单,直接统计两个字符串中128个字符出现的个数,然后就比较数量是否相等即可。

class Solution {
public:
    bool isAnagram(string s, string t) {
       map<char,int> maps;
       map<char,int> mapt;
       
       if(s.size()!=t.size()){
           return false;
       }
        
       for(int i = 0;i < s.size();++i){
           if(maps.find(s[i])!=maps.end()){
               maps[s[i]] += 1;
           }else{
               maps[s[i]] = 1;
           }
           
           if(mapt.find(t[i])!=mapt.end()){
               mapt[t[i]] += 1;
           }else{
               mapt[t[i]] = 1;
           }
       }
       
       for(int i = 0;i < t.size();++i){
           if(maps[s[i]]!=mapt[s[i]]){
               return false;
           }
       }
        
       return true;
    }
};
原文地址:https://www.cnblogs.com/mikemeng/p/8984832.html