【Lintcode】1025. Custom Sort String
阿新 • • 發佈:2020-12-12
技術標籤:# 棧、佇列、串及其他資料結構leetcode字串演算法雜湊表資料結構
題目地址:
https://www.lintcode.com/problem/custom-sort-string/description
給定兩個字串 s s s和 t t t,題目保證兩者都只含英文小寫字母,並且 s s s裡無重複字母。要求重排 t t t,使得 t t t的字母順序是按照 s s s裡字母順序定義的。不在 s s s裡的字母隨便排在哪兒。返回任意一個重排的結果即可。
先統計一下
t
t
t的每個字母出現次數,以雜湊表
c
c
c表示,然後再遍歷
s
s
s,如果
s
[
i
]
s[i]
s [i]出現了,則append到一個StringBuilder後面
c
[
s
[
i
]
]
c[s[i]]
c[s[i]]這麼多次。最後再把沒出現的字母也依次append到StringBuilder後面即可。程式碼如下:
public class Solution {
/**
* @param S: The given string S
* @param T: The given string T
* @return: any permutation of T (as a string) that satisfies this property
*/
public String customSortString(String S, String T) {
// Write your code here
int[] count = new int[26];
for (int i = 0; i < T.length(); i++) {
count[T.charAt(i) - 'a']++;
}
StringBuilder sb = new StringBuilder();
// 先處理S裡有的字母
for (int i = 0; i < S.length(); i++) {
int idx = S.charAt(i) - 'a';
while (count[idx] > 0) {
sb.append((char) ('a' + idx));
count[idx]--;
}
}
// 再處理沒有的
for (int i = 0; i < count.length; i++) {
if (count[i] == 0) {
continue;
}
for (int j = 0; j < count[i]; j++) {
sb.append((char) ('a' + i));
}
}
return sb.toString();
}
}
時空複雜度 O ( l t ) O(l_t) O(lt)。