1. 내 풀이
alphabet을 char로 해석해서, int값으로 내려놓으면 26개의 배열 내로 모든 알파벳이 어디에 있는지 인덱스를 알 수 있다.
class Solution {
public int[] solution(String s) {
int[] alphabet = new int[26];
int[] answer = new int[s.length()];
for(int i = 0; i<alphabet.length; i++){
alphabet[i] = -1;
}
for(int i = 0; i<s.length(); i++){
int ai = s.charAt(i) - 'a';
if(alphabet[ai] != -1) answer[i] = i - alphabet[ai];
else answer[i] = -1;
alphabet[ai] = i;
}
return answer;
}
}
2. 다른 분 풀이
Map을 사용하셨다. map의 getOrDefault함수도 사용하셨다.
원리는 같지만 훨씬 세련되게 풀었다. 보고 배워야지!
import java.util.*;
class Solution {
public int[] solution(String s) {
int[] answer = new int[s.length()];
HashMap<Character,Integer> map = new HashMap<>();
for(int i=0; i<s.length();i++){
char ch = s.charAt(i);
answer[i] = i-map.getOrDefault(ch,i+1);
map.put(ch,i);
}
return answer;
}
}
'코딩테스트 > Programmers' 카테고리의 다른 글
[프로그래머스] 숫자 문자열과 영단어 (0) | 2025.02.28 |
---|---|
[프로그래머스] 두 개 뽑아서 더하기 (0) | 2025.02.28 |
[프로그래머스] 시저 암호 (0) | 2025.02.26 |
[프로그래머스] 이상한 문자 만들기 (0) | 2025.02.26 |
[프로그래머스] 3진법 뒤집기 / 진법 변환 (0) | 2025.02.26 |