C++小白修仙记_LeetCode刷题_242 有效的字母异位词
242. 有效的字母异位词
给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的 字母异位词。
示例 1:
输入: s = "anagram", t = "nagaram"
输出: true
示例 2:
输入: s = "rat", t = "car"
输出: false
方法一:计数法
时间复杂度O(Nlogn) 空间复杂度O(N)
class Solution {
public:
    bool isAnagram(string s, string t) {
        if(s.size() != t.size())
        {
            return false;
        }
        vector<int>count(26,0);
        for(int i = 0; i < s.size(); i++)
        {
            char ch = s[i];
            count[ch - 'a']++;
        }
        for(int j = 0; j < t.size(); j++)
        {
            char ch = t[j];
            count[ch - 'a']--;
            if(count[ch - 'a'] < 0)
            {
                return false;
            }
        }
        return true;
    }
};
方法二:排序法
时间复杂度O(Nlogn) 空间复杂度O(N)
class Solution {
public:
    bool isAnagram(string s, string t) {
        if(s.size() != t.size())
        {
            return false;
        }
        sort(s.begin(),s.end());
        sort(t.begin(),t.end());
       if(s == t)
       return true;
       return false;
    }
};

 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号