美文网首页
Custom Sort String (Leetcode 791

Custom Sort String (Leetcode 791

作者: stepsma | 来源:发表于2018-06-13 02:55 被阅读0次

    A家的题。

    解法1直接sort,

    class Solution {
    public:
        string customSortString(string S, string T) {
            if(S.empty()){
                return T;
            }
            
            auto comp = [&S](const char c1, const char c2){
                return S.find(c1) < S.find(c2);
            };
            
            sort(T.begin(), T.end(), comp);
            return T;
        }
    };
    

    解法二:记下string T中每个char的个数,然后再loop S, 按照S的顺序recover出来

    class Solution {
    public:
    string customSortString(string S, string T) {
    unordered_map<char, int> mp;
    for(char c : T){
    mp[c]++;
    }

        string ret = "";
        
        for(char c : S){
            if(mp.count(c)){
                int cnt = mp[c];
                ret += string(cnt, c);
                mp.erase(c);
            }
            
        }
        
        for(auto it : mp){
            char c = it.first; int cnt = it.second;
            ret += string(cnt, c);
        }
        
        return ret;
    }
    

    };

    相关文章

      网友评论

          本文标题:Custom Sort String (Leetcode 791

          本文链接:https://www.haomeiwen.com/subject/nsydeftx.html