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 and s consist of lowercase English letters.
- All the characters of order are unique.
Solution
方法一:自定义排序
给每一个字母赋权值,第一个出现的字母赋为 1 ,第二个出现的赋为 2 ,以此类推;未出现的赋为 0 。根据权值从小到大排序原字符串即可。
class Solution {
public:
string customSortString(string order, string s) {
vector<int> val(26, 0);
for (int i = 0; i < order.size(); i++) {
val[order[i] - 'a'] = i + 1;
}
sort(s.begin(), s.end(), [&](char c0, char c1) {
return val[c0 - 'a'] < val[c1 - 'a'];
});
return s;
}
};
方法二:计数排序
对每一个 s 中的字符计数,根据 order 的顺序 append 即可,再把 order 中没有的 append 上去,返回构造的新字符串即可。
class Solution {
public:
string customSortString(string order, string s) {
vector<int> freq(26);
for (char ch: s) {
++freq[ch - 'a'];
}
string ans;
for (char ch: order) {
if (freq[ch - 'a'] > 0) {
ans += string(freq[ch - 'a'], ch);
freq[ch - 'a'] = 0;
}
}
for (int i = 0; i < 26; ++i) {
if (freq[i] > 0) {
ans += string(freq[i], i + 'a');
}
}
return ans;
}
};