[JAVA 문제 풀이] 260. 가장 가까운 같은 글자

프로그래머스 (142086)
Stupefyee's avatar
May 16, 2025
[JAVA 문제 풀이] 260. 가장 가까운 같은 글자
notion image
 

내가 작성한 코드

import java.util.*; class Solution { public int[] solution(String s) { int[] answer = new int[s.length()]; Map<Character, Integer> lastIndexMap = new HashMap<>(); for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); if (lastIndexMap.containsKey(ch)) { answer[i] = i - lastIndexMap.get(ch); // 현재 인덱스 - 마지막 등장 인덱스 } else { answer[i] = -1; // 처음 나온 문자 } lastIndexMap.put(ch, i); // 마지막 등장 인덱스 갱신 } 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; } }
  • getOrDefault(key, defaultValue)
    • Map 사용 시, 키가 존재하지 않아도 기본값을 지정해 안전하게 값 조회하는 메서드
    • key: 찾고 싶은 키
    • defaultValue: 키가 존재하지 않을 경우 반환할 기본값
Share article

stupefyee