[LeetCode] 791. Custom Sort String
阿新 • • 發佈:2018-07-21
tis call std letter this ica rev 大寫 repeated
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;
}
[LeetCode] 791. Custom Sort String