반응형
오랜만에 자바로 풀어보았다.
class Solution {
public int[] solution(String s) {
int answer[] = new int[s.length()];
int[] alphabet = new int[26]; // a : 0 ~ z : 25
for(int i = 0; i < s.length(); i++) {
if(alphabet[(s.charAt(i) - 'a')] == 0) {
answer[i] = -1;
} else {
answer[i] = i + 1 - alphabet[(s.charAt(i) - 'a')];
}
alphabet[(s.charAt(i) - 'a')] = i + 1;
}
return answer;
}
}
자바 다른사람의 풀이
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;
}
}
C++의 map처럼
JAVA에는 HashMap<Character, Integer> map = new HashMap<>()
그리고 getOrDefault를 통해, 없으면 디폴트 값을 지정할 수 있다.
파이썬.. 대단하다. 매우 짧다.
def solution(s):
answer = []
dic = dict() # dictionary
for i in range(len(s)): # idx 0 ~ len - 1 까지
if s[i] not in dic: # 엄청난 not in 연산자.. 직관적이고 대단하다.
answer.append(-1)
else:
answer.append(i - dic[s[i]])
dic[s[i]] = i
return answer
반응형
'[알고리즘 + 자료구조] > [프로그래머스]' 카테고리의 다른 글
[프로그래머스] 부대복귀 (0) | 2023.06.01 |
---|---|
프로그래머스 주차 요금 계산 (JAVA) (0) | 2022.12.15 |
프로그래머스 등굣길 (0) | 2022.10.04 |
프로그래머스 야근 지수 (0) | 2022.10.02 |
프로그래머스 최고의 집합 (0) | 2022.09.30 |