Coding Test/JAVA 코딩테스트 풀이정리(프로그래머스)

프로그래머스 스쿨 Lv.1 - 폰켓몬(최근 중복등장 거리 검사)
깝몬 2023. 12. 28. 00:06

문제

https://school.programmers.co.kr/learn/courses/30/lessons/142086

 

 

정답

class Solution {
    public int[] solution(String s) {
        
        int[] answer = new int[s.length()];
        
        answer[0]=-1;
        String[] spl = s.split("");
        for(int i=1;i<s.length();i++){
            answer[i]=-1;
            int hopCount=0;
            for(int j=i-1;j>=0;j--){
                hopCount++;
                if(spl[i].equals(spl[j])){
                    answer[i]=hopCount;
                    break;
                }
            }
        }
        return answer;
    }
}

 

이중 for문을 사용해 만약 앞에 해당 글자가 나타난다면 처리하는 문자를 사용했다.

 

쓰다보니 Map구조를 이용해서 풀었다면 더 처리시간이 짧게 걸릴 것 같았으니 나중에 다시한번 Map구조로 도전해보자.