##### Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/791.html

# 791. Custom Sort String (Medium)

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"
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.

Companies:

Related Topics:
String

## Solution 1.

• class Solution {
public String customSortString(String S, String T) {
Map<Character, Integer> map = new HashMap<Character, Integer>();
int sLength = S.length(), tLength = T.length();
for (int i = 0; i < sLength; i++)
map.put(S.charAt(i), i);
char[] tArray = T.toCharArray();
Character[] sortedArray = new Character[tLength];
for (int i = 0; i < tLength; i++)
sortedArray[i] = tArray[i];
Arrays.sort(sortedArray, new Comparator<Character>() {
public int compare(Character c1, Character c2) {
int order1 = map.getOrDefault(c1, 100);
int order2 = map.getOrDefault(c2, 100);
return order1 - order2;
}
});
for (int i = 0; i < tLength; i++)
tArray[i] = sortedArray[i];
return new String(tArray);
}
}

############

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();
}
}

• // OJ: https://leetcode.com/problems/custom-sort-string/
// Time: O(NlogN)
// Space: O(1)
class Solution {
public:
string customSortString(string order, string str) {
int priority[26] = {};
for (int i = 0; i < order.size(); ++i) priority[order[i] - 'a'] = i;
sort(begin(str), end(str), [&](int a, int b) { return priority[a - 'a'] < priority[b - 'a']; });
return str;
}
};

• 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)

############

from collections import Counter
class Solution(object):
def customSortString(self, S, T):
"""
:type S: str
:type T: str
:rtype: str
"""
count = Counter(T)
for s in S:
count[s] = 0
for c in count:

• 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('');
}


• 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
}
}