【Lintcode】1025. Custom Sort String
題目地址:
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)。
相關文章
- [LintCode] Permutation in String
- JavaScript object array sort by string bug All In OneJavaScriptObject
- 拼接數字(知識點:string的使用和sort的cmp)
- Custom
- Insertion Sort and Merge Sort
- graphite custom functionsFunction
- Unknown custom element: <> -
- CSS Custom Highlight APICSSAPI
- [Vue] Props: Custom ValidationVue
- [LintCode] Daily TemperaturesAI
- JavaScript sort()JavaScript
- Queue Sort
- topo sort
- sort排序排序
- [LintCode/LeetCode] Meeting RoomsLeetCodeOOM
- Lintcode 1263. Is Subsequence
- 【Lintcode】1189. Minesweeper
- Cypress系列(63)- 使用 Custom Commands
- golang sort.Sort () 排序演算法學習Golang排序演算法
- 關於stable_sort()和sort()的區別:
- sort()函式函式
- Leetcode Sort ColorsLeetCode
- Leetcode Sort ArrayLeetCode
- REPLACEMENT SELECTION SORT
- Sort Array By Parity
- Polyphase Merge Sort
- 【LeetCode刷題筆記(四十二)】之 1025. 除數博弈LeetCode筆記
- [LeetCode/LintCode] Largest Palindrome ProductLeetCode
- [LintCode/LeetCode] Contains Duplicate IIILeetCodeAI
- [LintCode] Check Full Binary Tree
- [LintCode/LeetCode] Remove Duplicate LettersLeetCodeREM
- [LintCode] 3Sum Smaller
- 【Lintcode】1615. The Result of Investment
- [LintCode] Binary Tree Level Order
- 【Lintcode】1736. Throw Garbage
- 【Lintcode】1665. Calculate Number
- 【Lintcode】1789. Distinguish UsernameNGUI
- 【Lintcode】1562. Number of RestaurantsREST