leetcode.com/problems/custom-sort-string/
S and T are strings composed of lowercase letters. In S, no letter occurs more than once.
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.
Return any permutation of T (as a string) that satisfies this property.
Example :
Input:
S = "cba"
T = "abcd"
Output: "cbad"
Explanation:
"a", "b", "c" appear in S, so the order of "a", "b", "c" should be "c", "b", and "a".
Since "d" does not appear in S, it can be at any position in T. "dcba", "cdba", "cbda" are also valid outputs.
class Solution {
public String customSortString(String S, String T) {
StringBuilder solution = new StringBuilder();
int[] charCheck = new int[26];
for (char temp : T.toCharArray()) {
charCheck[temp - 'a']++;
}
for (char temp : S.toCharArray()) {
while (charCheck[temp - 'a']-- > 0) {
solution.append(temp);
}
}
for (char temp = 'a'; temp <= 'z'; temp++) {
while (charCheck[temp - 'a']-- > 0) {
solution.append(temp);
}
}
return solution.toString();
}
}
'개발자 > algorithm' 카테고리의 다른 글
LeetCode, Maximum Depth of Binary Tree (Java) (0) | 2021.01.03 |
---|---|
LeetCode, Merge Two Binary Trees (Java) (0) | 2021.01.03 |
LeetCode, Check If Two String Arrays are Equivalent (Java) (0) | 2020.12.30 |
LeetCode, Minimum Number of Steps to Make Two Strings Anagram (Java) (0) | 2020.12.29 |
LeetCode, Goal Parser Interpretation (Java) (0) | 2020.12.29 |