Skip to content

Commit 4421795

Browse files
authored
Update Custom Sort String.java
1 parent b89f7fb commit 4421795

File tree

1 file changed

+11
-21
lines changed

1 file changed

+11
-21
lines changed

Medium/Custom Sort String.java

Lines changed: 11 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,16 @@
11
class Solution {
2-
public String customSortString(String S, String T) {
3-
Set<Character> set = new HashSet<>();
4-
for (int i = 0; i < S.length(); i++) {
5-
set.add(S.charAt(i));
6-
}
2+
public String customSortString(String order, String s) {
73
Map<Character, Integer> map = new HashMap<>();
8-
StringBuilder sb = new StringBuilder();
9-
for (char c : T.toCharArray()) {
10-
if (set.contains(c)) {
11-
map.put(c, map.getOrDefault(c, 0) + 1);
12-
}
13-
else {
14-
sb.append(c);
15-
}
16-
}
17-
for (int i = 0; i < S.length(); i++) {
18-
char c = S.charAt(i);
19-
int count = map.getOrDefault(c, 0);
20-
while (count-- > 0) {
21-
sb.append(c);
22-
}
4+
int position = 1;
5+
for (char c : order.toCharArray()) {
6+
map.put(c, position++);
237
}
24-
return sb.toString();
8+
return s.chars()
9+
.mapToObj(c -> (char) c)
10+
.sorted(Comparator.comparing(o -> map.getOrDefault(o, 0)))
11+
.collect(Collector.of(StringBuilder::new,
12+
StringBuilder::append,
13+
StringBuilder::append,
14+
StringBuilder::toString));
2515
}
2616
}

0 commit comments

Comments
 (0)