본문 바로가기
[알고리즘 + 자료구조]/[프로그래머스]

프로그래머스 가장 가까운 같은 글자

by Hevton 2022. 12. 14.
반응형

오랜만에 자바로 풀어보았다.

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

 

반응형