코드
class Solution {
public int[] solution(String s) {
int[] answer = new int[s.length()];
answer[0] = -1;
for (int i = 1; i < s.length();i++) {
int x = s.lastIndexOf(s.substring(i,i+1),i-1);
if (x != -1) {
answer[i] = i-x;
} else {
answer[i] = x;
}
}
return answer;
}
}
풀이
- 가장 첫 글자는 무조건 -1이다.
- lastIndexOf()를 사용하면, i-1 인덱스를 기준으로 s.substring(i,i+1)이 있는지 없는지를 확인한다.
- x가 -1이면 없다는 것이므로 answer[i]에 x를 넣는다
- x가 -1이 아닐경우 1-x를 넣는다.
'👨🏻💻알고리즘 > 프로그래머스' 카테고리의 다른 글
| [프로그래머스] Lv3. 단속 카메라 (0) | 2023.01.31 |
|---|---|
| [프로그래머스] Lv3. 등굣길 (0) | 2023.01.31 |
| [프로그래머스] Lv1. 푸드 파이트 대회 (0) | 2023.01.30 |
| [프로그래머스] Lv2. 모음사전 (0) | 2023.01.30 |
| [프로그래머스] Lv3. 단어 변환 (0) | 2023.01.29 |