Welcome to Subscribe On Youtube
791. Custom Sort String
Description
You are given two strings order and s. All the characters of order are unique and were sorted in some custom order previously.
Permute the characters of s so that they match the order that order was sorted. More specifically, if a character x occurs before a character y in order, then x should occur before y in the permuted string.
Return any permutation of s that satisfies this property.
Example 1:
Input: order = "cba", s = "abcd" Output: "cbad" Explanation: "a", "b", "c" appear in order, so the order of "a", "b", "c" should be "c", "b", and "a". Since "d" does not appear in order, it can be at any position in the returned string. "dcba", "cdba", "cbda" are also valid outputs.
Example 2:
Input: order = "cbafg", s = "abcd" Output: "cbad"
Constraints:
1 <= order.length <= 261 <= s.length <= 200orderandsconsist of lowercase English letters.- All the characters of
orderare unique.
Solutions
Solution 1: Sorting
A more straightforward idea is to use a hash table or array $d$ to record the position of each character in the string $order$, and then sort each character in the string $s$ according to its position in $d$. If a character is not in $d$, we can set its position to $0$.
Time complexity $O(m + n\times \log n)$, space complexity $O(m)$. Where $m$ and $n$ are the lengths of the strings $order$ and $s$ respectively.
Solution 2
We can also first count the number of occurrences of each character in $s$ and store it in the $cnt$ array.
Then sort the characters appearing in $order$ in the string $s$ in the order of $order$ and add them to the result string. Finally, the remaining characters are appended directly to the result string.
Time complexity $O(m+n)$, space complexity $O(m)$. where $m$ and $n$ are the lengths of the strings $order$ and $s$ respectively.
-
class Solution { public String customSortString(String order, String s) { int[] cnt = new int[26]; for (int i = 0; i < s.length(); ++i) { ++cnt[s.charAt(i) - 'a']; } StringBuilder ans = new StringBuilder(); for (int i = 0; i < order.length(); ++i) { char c = order.charAt(i); while (cnt[c - 'a']-- > 0) { ans.append(c); } } for (int i = 0; i < 26; ++i) { while (cnt[i]-- > 0) { ans.append((char) ('a' + i)); } } return ans.toString(); } } // Solution 2 class Solution { public String customSortString(String order, String s) { int[] cnt = new int[26]; for (int i = 0; i < s.length(); ++i) { ++cnt[s.charAt(i) - 'a']; } StringBuilder ans = new StringBuilder(); for (int i = 0; i < order.length(); ++i) { char c = order.charAt(i); while (cnt[c - 'a']-- > 0) { ans.append(c); } } for (int i = 0; i < 26; ++i) { while (cnt[i]-- > 0) { ans.append((char) ('a' + i)); } } return ans.toString(); } } -
class Solution { public: string customSortString(string order, string s) { int cnt[26] = {0}; for (char& c : s) ++cnt[c - 'a']; string ans; for (char& c : order) while (cnt[c - 'a']-- > 0) ans += c; for (int i = 0; i < 26; ++i) if (cnt[i] > 0) ans += string(cnt[i], i + 'a'); return ans; } }; // Solution 2 class Solution { public: string customSortString(string order, string s) { int cnt[26] = {0}; for (char& c : s) ++cnt[c - 'a']; string ans; for (char& c : order) while (cnt[c - 'a']-- > 0) ans += c; for (int i = 0; i < 26; ++i) if (cnt[i] > 0) ans += string(cnt[i], i + 'a'); return ans; } }; -
class Solution: def customSortString(self, order: str, s: str) -> str: cnt = Counter(s) ans = [] for c in order: ans.append(c * cnt[c]) cnt[c] = 0 for c, v in cnt.items(): ans.append(c * v) return ''.join(ans) # Solution 2 class Solution: def customSortString(self, order: str, s: str) -> str: cnt = Counter(s) ans = [] for c in order: ans.append(c * cnt[c]) cnt[c] = 0 for c, v in cnt.items(): ans.append(c * v) return ''.join(ans) -
func customSortString(order string, s string) string { cnt := [26]int{} for _, c := range s { cnt[c-'a']++ } ans := []rune{} for _, c := range order { for cnt[c-'a'] > 0 { ans = append(ans, c) cnt[c-'a']-- } } for i, v := range cnt { for j := 0; j < v; j++ { ans = append(ans, rune('a'+i)) } } return string(ans) } // Solution 2 func customSortString(order string, s string) string { cnt := [26]int{} for _, c := range s { cnt[c-'a']++ } ans := []rune{} for _, c := range order { for cnt[c-'a'] > 0 { ans = append(ans, c) cnt[c-'a']-- } } for i, v := range cnt { for j := 0; j < v; j++ { ans = append(ans, rune('a'+i)) } } return string(ans) } -
function customSortString(order: string, s: string): string { const toIndex = (c: string) => c.charCodeAt(0) - 'a'.charCodeAt(0); const count = new Array(26).fill(0); for (const c of s) { count[toIndex(c)]++; } const ans: string[] = []; for (const c of order) { const i = toIndex(c); ans.push(c.repeat(count[i])); count[i] = 0; } for (let i = 0; i < 26; i++) { if (!count[i]) continue; ans.push(String.fromCharCode('a'.charCodeAt(0) + i).repeat(count[i])); } return ans.join(''); } // Solution 2 function customSortString(order: string, s: string): string { const toIndex = (c: string) => c.charCodeAt(0) - 'a'.charCodeAt(0); const count = new Array(26).fill(0); for (const c of s) { count[toIndex(c)]++; } const ans: string[] = []; for (const c of order) { const i = toIndex(c); ans.push(c.repeat(count[i])); count[i] = 0; } for (let i = 0; i < 26; i++) { if (!count[i]) continue; ans.push(String.fromCharCode('a'.charCodeAt(0) + i).repeat(count[i])); } return ans.join(''); } -
impl Solution { pub fn custom_sort_string(order: String, s: String) -> String { let mut count = [0; 26]; for c in s.as_bytes() { count[(c - b'a') as usize] += 1; } let mut ans = String::new(); for c in order.as_bytes() { for _ in 0..count[(c - b'a') as usize] { ans.push(char::from(*c)); } count[(c - b'a') as usize] = 0; } for i in 0..count.len() { for _ in 0..count[i] { ans.push(char::from(b'a' + (i as u8))); } } ans } } // Solution 2 impl Solution { pub fn custom_sort_string(order: String, s: String) -> String { let mut count = [0; 26]; for c in s.as_bytes() { count[(c - b'a') as usize] += 1; } let mut ans = String::new(); for c in order.as_bytes() { for _ in 0..count[(c - b'a') as usize] { ans.push(char::from(*c)); } count[(c - b'a') as usize] = 0; } for i in 0..count.len() { for _ in 0..count[i] { ans.push(char::from(b'a' + (i as u8))); } } ans } }