seunghyun Note

[프로그래머스] - 가장 가까운 같은 글자 with JAVA 본문

코딩테스트/백준

[프로그래머스] - 가장 가까운 같은 글자 with JAVA

승숭슝현 2024. 1. 6. 21:52

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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

문제 풀이


문제를 풀 때 고민이 정말 많았다. 
배열을 2중 for문으로 순회하고 배열값이 같을 때 (index가 다를 경우) j를 Max로 설정하고 값을 추가해준다.

이해가 안될때는 그리기.

 

class Solution {
    public int[] solution(String s) {
        int[] answer = new int[s.length()];
        char[] ch = new char[s.length()];
        
        //문자열 배열로 추가해주기.
        for(int i=0;i<answer.length;i++){
            ch[i] = s.charAt(i);
        }
        
        int i,j;
        
        // 배열 순회
        for(i=0;i<ch.length;i++){
            int max=0;
            int cnt=0;
            for(j=0;j<i;j++){
                if(ch[i] == ch[j]){
                        if(j > max) max = j;
                    cnt++;
                }
            }
            if(cnt <=0) answer[i] = -1;
            else answer[i] = i-max;

        }
        return answer;
    }   
}
728x90