📝문제 설명
📢입출력 예시
✏️문제 풀이
1. 배열 풀이
class Solution {
public int[] solution(String s) {
int[] answer = new int[s.length()];
int[] alph = new int[26];
for(int i=0; i<26; i++){
alph[i] = -1;
}
for(int i=0; i<s.length(); i++){
char c = s.charAt(i);
if(alph[c-'a'] != -1){
answer[i] = i - alph[c-'a'];
}else{
answer[i] = -1;
}
alph[c-'a'] = i;
}
return answer;
}
}
2. Map 풀이
import java.util.*;
class Solution {
public int[] solution(String s) {
int[] answer = new int[s.length()];
Map<Character, Integer> map = new HashMap<>();
for(int i=0; i<s.length(); i++){
char c = s.charAt(i);
if(map.containsKey(c)){
answer[i] = i - map.get(c);
}else{
answer[i] = -1;
}
map.put(c,i);
}
return answer;
}
}
💡새로 알게된 점
'📖Algorithm > Simulation, Math' 카테고리의 다른 글
JAVA [Algorithm] - 백준 1193 분수 찾기 (0) | 2024.12.19 |
---|---|
JAVA [Programmers] 2단계 - 연속 부분 수열 합의 개수 (0) | 2024.12.06 |
자바 [Programmers] 2단계 - 점프와 순간이동 (0) | 2024.12.03 |
자바 [Programmers] 2단계 - JadenCase 문자열 만들기 (0) | 2024.11.28 |
자바 [Programmers] 2단계 - 이진 변환 반복하기 (0) | 2024.11.28 |