Problem
You are given two strings order and s. All the words 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.
Examples
Example 1:
|
|
Example 2:
|
|
Solution
Method 1 - Sorting
To solve this problem, we need to rearrange the characters of the string s
to follow the order specified in order
. Here is a step-by-step approach to achieve this:
- Create a Mapping: Create a priority map from the custom order string, where each character is assigned an index based on its position in the
order
string. - Count Characters in s: Count the occurrences of each character in
s
. This helps in easily constructing the resultant string based on the sorted order. - Construct the Result: Iterate through the
order
string and add characters to the result based on the count from the previous step. Finally, add any characters froms
that were not present inorder
.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n + m)
wheren
is the length ofs
andm
is the length oforder
. This includes creating the priority map, counting occurrences, and constructing the result. - 🧺 Space complexity:
O(n + m)
for storing the counts of characters and the resultant string.