코딩테스트

[C# 프로그래머스] Lv1 가장 가까운 같은 글자

routine96 2025. 3. 1. 15:29

 

 

내 풀이 방법

 

Dictionary 사용

using System;
using System.Collections.Generic;

public class Solution {
    public int[] solution(string s) {
        int[] answer = new int[s.Length];
        
        Dictionary<char, int> dic = new Dictionary<char, int>();
        
        for(int i = 0; i < s.Length; i++)
        {
            // dic에 문자와 같은 키값이 존재하지 않는다면 answer[i]에 -1을 저장하고 
            // Key(문자) 값과 Value(인덱스)를 추가한다.
            if(!dic.ContainsKey(s[i]))
            {
                answer[i] = -1;
                dic.Add(s[i], i);
                continue;
            }
            
            // dic에 키 값이 존재하는 경우
            // 현재 인덱스 - 키 값의 인덱스를 answer[i] 저장 후 딕셔너리 키 값에 현재 인덱스로 변경
            answer[i] = i - dic[s[i]];
            dic[s[i]] = i;
        }
        
        return answer;
    }
}

 

 

다른 사람 풀이

using System;

public class Solution {
    public int[] solution(string s) {
        int[] answer = new int[s.Length];
        answer[0] = -1;

        for (int i = 1; i < s.Length; i++)
        {
            int idx = s.Substring(0, i).LastIndexOf(s[i]);

            answer[i] = idx == -1 ? -1 : i - s.Substring(0, i).LastIndexOf(s[i]);
        }

        return answer;
    }
}

 

Substring과 LastIndexOf를 활용

Substring(0, i) 문자열의 0번째 인덱스에서 i 만큼 문자열을 자른다.

LastIndexOf(s[i]) 문자열 뒤에서 부터 s[i]의 문자열이 있는지 검사 있다면 해당 인덱스를 반환하고 없으면 -1 리턴

그러므로 idx가 -1이면 해당하는 문자가 없고, 있다면 해당 인덱스를 리턴해 현재 i 값에서 빼준다.