leetcode 242 有效的字母异位词

 

使用排序:O(2N)空间,O(2NlogN)时间

class Solution {
public:
    bool isAnagram(string s, string t) {
        //使用string 模板类的sort排序功能,异位词排序结束必然相等;
        sort(s.begin(),s.end());
        sort(t.begin(),t.end());
        if(s==t)
            return true;
        else
            return false;
    }
};

使用哈希表的方法:O(2N)空间,O(2N)时间

class Solution {
public:
    bool isAnagram(string s, string t) {
        
        string a="00000000000000000000000000";
        for(int i=0;i<s.size();i++){
            a[s[i]-'a']+=1;
        }
        string b="00000000000000000000000000";
        for(int i=0;i<t.size();i++){
            b[t[i]-'a']+=1;
        }
        return a==b;
    }
};
原文地址:https://www.cnblogs.com/joelwang/p/10686323.html