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 <= 26
1 <= s.length <= 200
order
ands
consist of lowercase English letters.- All the characters of
order
are unique.
class Solution:
def customSortString(self, order: str, s: str) -> str:
cs = list(s)
m = {v: i for i, v in enumerate(order)}
cs.sort(key=lambda x: m.get(x, -1))
return ''.join(cs)
class Solution:
def customSortString(self, order: str, s: str) -> str:
cnt = Counter(s)
ans = []
for c in order:
ans.append(cnt[c] * c)
cnt[c] = 0
for c in s:
ans.append(cnt[c] * c)
cnt[c] = 0
return ''.join(ans)
class Solution {
public String customSortString(String order, String s) {
Map<Character, Integer> m = new HashMap<>();
for (int i = 0; i < order.length(); ++i) {
m.put(order.charAt(i), i);
}
List<Character> cs = new ArrayList<>();
for (char c : s.toCharArray()) {
cs.add(c);
}
cs.sort((a, b) -> m.getOrDefault(a, -1) - m.getOrDefault(b, -1));
StringBuilder ans = new StringBuilder();
for (char c : cs) {
ans.append(c);
}
return ans.toString();
}
}
class Solution {
public String customSortString(String order, String s) {
int[] cnt = new int[26];
for (char c : s.toCharArray()) {
++cnt[c - 'a'];
}
StringBuilder ans = new StringBuilder();
for (char c : order.toCharArray()) {
while (cnt[c - 'a']-- > 0) {
ans.append(c);
}
}
for (char c : s.toCharArray()) {
while (cnt[c - 'a']-- > 0) {
ans.append(c);
}
}
return ans.toString();
}
}
class Solution {
public:
string customSortString(string order, string s) {
vector<int> cnt(26);
for (char c : s) ++cnt[c - 'a'];
string ans = "";
for (char c : order) {
while (cnt[c - 'a']-- > 0) {
ans += c;
}
}
for (char c : s) {
while (cnt[c - 'a']-- > 0) {
ans += c;
}
}
return ans;
}
};
func customSortString(order string, s string) string {
cnt := make([]int, 26)
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 _, c := range s {
for cnt[c-'a'] > 0 {
ans = append(ans, c)
cnt[c-'a']--
}
}
return string(ans)
}