-
Notifications
You must be signed in to change notification settings - Fork 0
/
가장 가까운 같은 글자.java
38 lines (29 loc) · 996 Bytes
/
가장 가까운 같은 글자.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// 가장 가까운 같은 글자 (https://school.programmers.co.kr/learn/courses/30/lessons/142086)
import java.util.*;
class Solution {
public int[] solution(String s) {
char[] chars = s.toCharArray();
int[] res = new int[chars.length];
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < chars.length; i++) {
if (!map.containsKey(chars[i])) {
res[i] = -1;
map.put(chars[i], i);
continue;
}
res[i] = i - map.get(chars[i]);
map.put(chars[i], i);
}
return res;
}
public int[] solution2(String s) {
char[] chars = s.toCharArray();
int[] res = new int[chars.length];
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < chars.length; i++) {
res[i] = i - map.getOrDefault(chars[i], i + 1);
map.put(chars[i], i);
}
return res;
}
}