-
Notifications
You must be signed in to change notification settings - Fork 564
Expand file tree
/
Copy path14. Custom Sort String.cpp
More file actions
57 lines (47 loc) · 1.34 KB
/
14. Custom Sort String.cpp
File metadata and controls
57 lines (47 loc) · 1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/*
Custom Sort String
==================
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:
order has length at most 26, and no character is repeated in order.
str has length at most 200.
order and str consist of lowercase letters only.
*/
class Solution
{
public:
string customSortString(string A, string B)
{
vector<int> bucket(26, 0);
for (auto &i : B)
bucket[i - 'a']++;
B = "";
for (auto &i : A)
{
while (bucket[i - 'a'] > 0)
{
B += i;
bucket[i - 'a']--;
}
}
for (int i = 0; i < 26; ++i)
{
while (bucket[i] > 0)
{
B += (i + 'a');
bucket[i]--;
}
}
return B;
}
};