|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import java.util.HashMap; |
| 4 | +import java.util.Map; |
| 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 | +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); |
| 52 | + } |
| 53 | + } |
| 54 | + return sb.toString(); |
| 55 | + } |
| 56 | + } |
| 57 | +} |
0 commit comments