Skip to content

Commit 399b9c9

Browse files
committed
Refactored one solution
1 parent 1b66fce commit 399b9c9

File tree

1 file changed

+23
-24
lines changed

1 file changed

+23
-24
lines changed

Medium/Custom Sort String.java

Lines changed: 23 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,26 @@
11
class Solution {
2-
public String customSortString(String S, String T) {
3-
int[] counter = new int[26];
4-
for (char c : T.toCharArray()) {
5-
counter[c - 'a']++;
6-
}
7-
8-
StringBuilder sb = new StringBuilder();
9-
for (char c : S.toCharArray()) {
10-
int count = counter[c - 'a'];
11-
for (int i = 0; i < count; i++) {
12-
sb.append(c);
13-
}
14-
15-
counter[c - 'a'] = 0;
16-
}
17-
18-
for (char c ='a'; c <= 'z'; c++) {
19-
int count = counter[c - 'a'];
20-
for (int i = 0; i < count; i++) {
21-
sb.append(c);
22-
}
23-
}
24-
25-
return sb.toString();
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));
266
}
7+
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+
}
23+
}
24+
return sb.toString();
25+
}
2726
}

0 commit comments

Comments
 (0)