Leetcode - Custom Sort String
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.
Solution,#
κ΅μ§ν©λ§ λ½μλ΄μ νλ©΄ λλ€. μ΄κ²λ νλ μλ μ νμ΄μ λ€μ νλ©΄ λ μ΄μκ² ν μ μμ κ² κ°λ€.
class Solution {
public String customSortString(String order, String str) {
Map<Integer, Character> a = new HashMap<>();
Map<Character, Integer> o = new HashMap<>();
for(int i = 0; i < order.length(); ++i) {
o.put(order.charAt(i), i);
a.put(i, order.charAt(i));
}
StringBuilder result = new StringBuilder();
List<Integer> j = new ArrayList<>();
for(int i = 0; i < str.length(); ++i) {
char item = str.charAt(i);
if (o.containsKey(item)) j.add(o.get(item));
else result.append(item);
}
Collections.sort(j);
for(Integer item : j) {
result.append(a.get(item));
}
return result.toString();
}
}
Read other posts
COMMENTS