[코테 풀이] Shortest Distance to a Character

시내·2024년 7월 28일
0

Q_821) Shortest Distance to a Character

출처 : https://leetcode.com/problems/shortest-distance-to-a-character/

Given a string s and a character c that occurs in s, return an array of integers answer where answer.length == s.length and answer[i] is the distance from index i to the closest occurrence of character c in s.

The distance between two indices i and j is abs(i - j), where abs is the absolute value function.

 class Solution {
    public int[] shortestToChar(String s, char c) {
        int[] answer = new int[s.length()];
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == c) answer[i] = 0;
            else answer[i] = Integer.MAX_VALUE;
        }
        for (int i = 0; i < s.length() - 1; i++) {
            if (answer[i] == Integer.MAX_VALUE) continue;
            else answer[i + 1] = Math.min(answer[i + 1], answer[i] + 1);
        }
        for (int i = s.length()-1; i > 0; i--) {
            answer[i - 1] = Math.min(answer[i - 1], answer[i] + 1);
        }
        return answer;
    }
}

🙈 풀이 참조해서 푼 문제

1) s char를 iterate하면서 c와 일치하는 경우는 0으로, 그렇지 않으면 Integer.MAX_VALUE로 값을 세팅한다.

2) 왼쪽->오른쪽 확인
answer[]를 iterate 하면서 Integer.MAX_VALUE가 아니라면, 즉 c가 아니라면, answer[i + 1]answer[i + 1]answer[i] + 1 중 최솟값으로 세팅한다.

3) 오른쪽->왼쪽 확인
answer[]를 다시 iterate 하면서 answer[i - 1]answer[i - 1]answer[i] + 1 중 최솟값으로 값을 업데이트한다.

profile
contact 📨 ksw08215@gmail.com

0개의 댓글