HashMap의 중복 키 값을 허용하지 않는(업데이트) 성질을 활용하여 문제를 풀었다.
문자와 문자의 인덱스를 저장할 HashMap을 만들어서
1. Map에 값이 없을 경우는 처음 나온 문자이므로 -1 삽입
2. Map에 값이 있는 경우는 현재 반복문의 인덱스와 값을 빼면 둘 간의 거리 차이를 삽입
NearSameWord.java
package com.example.Programmers.Lv1;
import java.util.HashMap;
import java.util.Map;
/**
* 프로그래머스 Lv1 - 가장 가까운 같은 글자
*/
public class NearSameWord {
public int[] solution(String s) {
Map<String, Integer> map = new HashMap<>();
String[] arr = s.split("");
int[] answer = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
Integer val = map.get(arr[i]);
map.put(arr[i], i);
if (val == null) {
answer[i] = -1;
} else {
answer[i] = i - val;
}
}
return answer;
}
}
NearSameWordTest.java
package com.example.Programmers.Lv1;
import static org.junit.Assert.assertArrayEquals;
import org.junit.Test;
public class NearSameWordTest {
@Test
public void nearSameWordTest() {
NearSameWord nsw = new NearSameWord();
int[] result1 = nsw.solution("banana");
int[] result2 = nsw.solution("foobar");
int[] expected1 = { -1, -1, -1, 2, 2, 2 };
int[] expected2 = { -1, -1, 1, -1, -1, -1 };
assertArrayEquals(expected1, result1);
assertArrayEquals(expected2, result2);
}
}