|
| 1 | +// Runtime: 0 ms (Top 100.0%) | Memory: 41.60 MB (Top 38.18%) |
| 2 | + |
1 | 3 | class Solution {
|
2 |
| - public String customSortString(String order, String s) { |
3 |
| - if(s.length() <= 1) return s; |
4 |
| - |
5 |
| - StringBuilder finalString = new StringBuilder(); |
6 |
| - HashMap<Character, Integer> hm = new HashMap<>(); |
7 |
| - |
8 |
| - for(int i = 0; i < s.length(); i++) { |
9 |
| - char actualChar = s.charAt(i); |
| 4 | + public String customSortString(String X, String Y) { |
| 5 | + //char count of string Y |
| 6 | + int[] charCount = new int[26]; |
| 7 | + for(char c : Y.toCharArray()){ |
| 8 | + charCount[c - 'a']++; |
| 9 | + } |
| 10 | + |
| 11 | + StringBuilder sb = new StringBuilder(); |
10 | 12 |
|
11 |
| - if(order.indexOf(actualChar) == -1) { |
12 |
| - finalString.append(actualChar); |
13 |
| - } else { |
14 |
| - hm.put(actualChar, hm.getOrDefault(actualChar, 0) + 1); |
| 13 | + //first store char in same order of String X |
| 14 | + for(char c : X.toCharArray()){ |
| 15 | + while(charCount[c - 'a'] --> 0){ |
| 16 | + sb.append(c); |
| 17 | + } |
15 | 18 | }
|
16 |
| - } |
17 |
| - |
18 |
| - for(int i = 0; i < order.length(); i++) { |
19 |
| - char actualChar = order.charAt(i); |
20 | 19 |
|
21 |
| - if (hm.get(actualChar) != null){ |
22 |
| - for(int j = 0; j < hm.get(actualChar); j++) { |
23 |
| - finalString.append(actualChar); |
24 |
| - } |
| 20 | + //now store remaining char of string Y |
| 21 | + for(int i = 0; i < 26; i++){ |
| 22 | + char c = (char)('a' + i); |
| 23 | + while(charCount[i] --> 0){ |
| 24 | + sb.append(c); |
| 25 | + } |
25 | 26 | }
|
26 |
| - } |
27 |
| - |
28 |
| - return finalString.toString(); |
| 27 | + |
| 28 | + return sb.toString(); |
29 | 29 | }
|
30 | 30 | }
|
0 commit comments