LintCode:字符串置换211

Hash表思路,时间复杂度为O(n),附加空间复杂度O(n)

class Solution {
public:
    /*
     * @param A: a string
     * @param B: a string
     * @return: a boolean
     */
     //思路:将字符串中的每一个值映射到hash表中,统计出现次数,然后比较是否相等
    bool Permutation(string A, string B) {
        // write your code here
        //Hash表:ASCII码一共128个字符
        int TempA[127] = {0};
        int TempB[127] = {0};

        if(A.size() != B.size()){
            return false;
        }

        //统计计数
        for(int i = 0 ;i//将本字符的ASCII码与空格的ASCII码相减,得到Hash的key
            TempA[A.at(i)]++;
            TempB[B.at(i)]++;
        }

        //比较是否相等
        for(int i = 0 ;iif(TempA[i] != TempB[i]){
                return false;
            }

        }
        return true;
    }
};

排序思路,最快O(nlogn)

class Solution {
public:
    /*
     * @param A: a string
     * @param B: a string
     * @return: a boolean
     */
     //思路:将字符串排序后,判断排序后是否相等
    bool Permutation(string A, string B) {
        // write your code here

        if(A.size() != B.size()){
            return false;
        }

        sort(A.begin(),A.end());
        sort(B.begin(),B.end());
        if(A == B){
            return true;
        }

        return false;
    }
};

你可能感兴趣的:(LintCode算法)