|
3 | 3 | import java.util.HashMap;
|
4 | 4 | import java.util.Map;
|
5 | 5 |
|
6 |
| -/** |
7 |
| - * 791. Custom Sort String |
8 |
| -
|
9 |
| - S and T are strings composed of lowercase letters. In S, no letter occurs more than once. |
10 |
| -
|
11 |
| - S was sorted in some custom order previously. We want to permute the characters of T so that they match the order that S was sorted. More specifically, if x occurs before y in S, then x should occur before y in the returned string. |
12 |
| -
|
13 |
| - Return any permutation of T (as a string) that satisfies this property. |
14 |
| -
|
15 |
| - Example : |
16 |
| - Input: |
17 |
| - S = "cba" |
18 |
| - T = "abcd" |
19 |
| - Output: "cbad" |
20 |
| - Explanation: |
21 |
| - "a", "b", "c" appear in S, so the order of "a", "b", "c" should be "c", "b", and "a". |
22 |
| - Since "d" does not appear in S, it can be at any position in T. "dcba", "cdba", "cbda" are also valid outputs. |
23 |
| -
|
24 |
| - Note: |
25 |
| -
|
26 |
| - S has length at most 26, and no character is repeated in S. |
27 |
| - T has length at most 200. |
28 |
| - S and T consist of lowercase letters only. |
29 |
| -
|
30 |
| - */ |
31 | 6 | public class _791 {
|
32 |
| - public static class Solution1 { |
33 |
| - public String customSortString(String S, String T) { |
34 |
| - Map<Character, Integer> map = new HashMap<>(); |
35 |
| - for (char c : T.toCharArray()) { |
36 |
| - map.put(c, map.getOrDefault(c, 0) + 1); |
37 |
| - } |
38 |
| - StringBuilder sb = new StringBuilder(); |
39 |
| - for (char c : S.toCharArray()) { |
40 |
| - if (map.containsKey(c)) { |
41 |
| - int count = map.get(c); |
42 |
| - while (count-- > 0) { |
43 |
| - sb.append(c); |
44 |
| - } |
45 |
| - map.remove(c); |
46 |
| - } |
47 |
| - } |
48 |
| - for (char c : map.keySet()) { |
49 |
| - int count = map.get(c); |
50 |
| - while (count-- > 0) { |
51 |
| - sb.append(c); |
| 7 | + public static class Solution1 { |
| 8 | + public String customSortString(String S, String T) { |
| 9 | + Map<Character, Integer> map = new HashMap<>(); |
| 10 | + for (char c : T.toCharArray()) { |
| 11 | + map.put(c, map.getOrDefault(c, 0) + 1); |
| 12 | + } |
| 13 | + StringBuilder sb = new StringBuilder(); |
| 14 | + for (char c : S.toCharArray()) { |
| 15 | + if (map.containsKey(c)) { |
| 16 | + int count = map.get(c); |
| 17 | + while (count-- > 0) { |
| 18 | + sb.append(c); |
| 19 | + } |
| 20 | + map.remove(c); |
| 21 | + } |
| 22 | + } |
| 23 | + for (char c : map.keySet()) { |
| 24 | + int count = map.get(c); |
| 25 | + while (count-- > 0) { |
| 26 | + sb.append(c); |
| 27 | + } |
| 28 | + } |
| 29 | + return sb.toString(); |
52 | 30 | }
|
53 |
| - } |
54 |
| - return sb.toString(); |
55 | 31 | }
|
56 |
| - } |
57 | 32 | }
|
0 commit comments