Description
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:
1Input: order = "cba", s = "abcd"
2Output: "cbad"
3Explanation:
4"a", "b", "c" appear in order, so the order of "a", "b", "c" should be "c", "b", and "a".
5Since "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:
1Input: order = "cbafg", s = "abcd"
2Output: "cbad"
Constraints:
1 <= order.length <= 261 <= s.length <= 200orderandsconsist of lowercase English letters.- All the characters of
orderare unique.
Solution
In this problem essentially, we want to track number of occurrences of characters in order string and verify if s string contains which of the characters. If those are available, add them to string builder as long as count > 0. Once we have run out of characters from order string, insert the remaining characters from s string.
To track count of each character, we can either store them in Map<Character, Integer> or an array of size 26 because all characters are lowercase English characters.
Using HashMap
1class Solution {
2 public String customSortString (String order, String s) {
3 Map<Character, Integer> map = new HashMap<>();
4 for (char c : s.toCharArray()) {
5 map.put(c, map.getOrDefault(c, 0) + 1);
6 }
7 StringBuilder sb = new StringBuilder();
8 for (char c : order.toCharArray()) {
9 while (map.getOrDefault(c, -1) > 0) {
10 sb.append(c);
11 map.put(c, map.getOrDefault(c, 0) - 1);
12 }
13 }
14 for (char c : map.keySet()) {
15 while (map.getOrDefault(c, -1) > 0) {
16 sb.append(c);
17 map.put(c, map.getOrDefault(c, 0) - 1);
18 }
19 }
20 return sb.toString();
21 }
22}
- Time Complexity:
O(m * n)wherem = size of orderandn = length of s - Space Complexity:
O(k)wherekis the number of unique characters in strings.
Using Array
1class Solution {
2 public String customSortString(String order, String s) {
3 int[] count = new int[26];
4 for (char c : s.toCharArray()) {
5 count[c - 'a']++;
6 }
7
8 StringBuilder sb = new StringBuilder();
9 for (char c : order.toCharArray()) {
10 while (count[c - 'a']-- > 0) {
11 sb.append(c);
12 }
13 }
14
15 for (char c = 'a'; c <= 'z'; c++) {
16 while (count[c - 'a']-- > 0) {
17 sb.append(c);
18 }
19 }
20
21 return sb.toString();
22 }
23}
- Time Complexity:
O(m * n)wherem = size of orderandn = length of s - Space Complexity:
O(1)because we are creating an array of size 26 all the time regardless of size of input.


Comments