[LeetCode] 791. Custom Sort String

S and T are strings composed of lowercase letters. In S, no letter occurs more than once.

S was sorted in some custom order previously. We want to permute the characters of T so that they match the order that S was sorted. More specifically, if x occurs before y in S, then x should occur before y in the returned string.

Return any permutation of T (as a string) that satisfies this property.

Example :
Input: 
S = "cba"
T = "abcd"
Output: "cbad"
Explanation: 
"a", "b", "c" appear in S, so the order of "a", "b", "c" should be "c", "b", and "a". 
Since "d" does not appear in S, it can be at any position in T. "dcba", "cdba", "cbda" are also valid outputs.

Note:

S has length at most 26, and no character is repeated in S.
T has length at most 200.
S and T consist of lowercase letters only.

将字符串T 按 字符串S中字符的顺序 排序

我的思路是先统计字符串T中各字符的数量,存到一个数组里,然后把在字符串S中存在的字符先拿出来,数量归0,再对这个数组循环一次,把剩下的字符也取出来,时间复杂度为\(O(n^2)\)

string customSortString(string S, string T)
{
    string result;

    int div[26] = {0};
    char chars[26] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
    for (int i = 0; i < T.length(); i++)
    {
        int index = T[i] - 'a';
        div[index]++;
    }

    for (int j = 0; j < S.length(); j++)
    {
        int index = S[j] - 'a';

        for (int k = 0; k < div[index]; div[index]--)
        {
            result += chars[index];
        }
    }

    for (int m = 0; m < 26; m++)
    {
        for (int n = 0; n < div[m]; n++)
        {
            result += chars[m];
        }
    }

    return result;
}

再看看LeetCode上大佬的代码,时间复杂度为\(O(n),\)注释是我写的

// S "kqep"
// T "rpekeq"
string customSortString(string S, string T) {
        vector<char> c2C(26, ' '); // 存顺序,长度为26,对应26个小写字母这里用的A,B,C,D代表顺序,而且大写字母的ASCII比小写字母小,后面排序能保证不在字符串S中的字符被排到后面
        vector<char> A2a(26, ' '); // 存值
        char C = 'A';
        // 这个循环结束后,c2C中字母对应的位置被填上A,B,C, D, 标记S中字母的顺序,即[{'e' : 'C'}, {'k' : 'A'}, {'p' : 'D'}, {'q' : 'B'}]
        // A2a变成[{'A' : 'k'}, {'B' : 'q'}, {'C' : 'e'}, {'D' : 'p'}]
        // 以上的[{}] 并不代表vector实际的样子,只是为了方便表达
        for (auto c : S) {
            c2C[c-'a'] = C;
            A2a[C-'A'] = c;
            C++;
        }
        string sT = "";
        
        //这个循环结束后sT变成 "rDCACB"
        for (auto c : T) {
            if (c2C[c-'a'] != ' ') {
                sT += c2C[c -'a'];
            } else {
                sT += c;
            }
        }
        std::sort(sT.begin(), sT.end());
        cout << sT << endl; // "ABCCDr"
        string res;
        // 把A B C D映射回 k q e p
        for (auto C : sT) {
            if (C >= 'A' && C <= 'Z' && A2a[C-'A'] != ' ') {
                res += A2a[C-'A'];
            } else {
                res += C;
            }
                
        }
        return res;
    }
posted @ 2018-07-21 18:38  arcsinW  阅读(142)  评论(0编辑  收藏  举报