order and str are strings composed of lowercase letters. In order, no letter occurs more than once.
order was sorted in some custom order previously. We want to permute the characters of str so that they match the order that order was sorted. More specifically, if x occurs before y in order, then x should occur before y in the returned string.
Return any permutation of str (as a string) that satisfies this property.
Example: Input: order = "cba" str = "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.
Note:
orderhas length at most26, and no character is repeated inorder.strhas length at most200.orderandstrconsist of lowercase letters only.
class Solution {
public:
string customSortString(string order, string str) {
vector<int> str_map(26, 0); // [1, 1, 1, 1, 0, 0 ..]
for (auto ch : str) {
str_map[ch - 'a']++;
}
// better to use map.
string ans;
for (auto ch : order) {
while (str_map[ch - 'a'] > 0) {
ans += string(1, ch);
str_map[ch - 'a']--;
}
}
for (int i = 0; i < 26; i++) {
while (str_map[i] > 0) {
ans += string(1, 'a' + i);
str_map[i]--;
}
}
return ans;
}
};
No comments:
Post a Comment