Skip to content

[week1] 가장 가까운 같은 글자#5

Open
ShinHyeongcheol wants to merge 2 commits intoSOPT-all:mainfrom
ShinHyeongcheol:week1/hyeongcheol-shin
Open

[week1] 가장 가까운 같은 글자#5
ShinHyeongcheol wants to merge 2 commits intoSOPT-all:mainfrom
ShinHyeongcheol:week1/hyeongcheol-shin

Conversation

@ShinHyeongcheol
Copy link

@ShinHyeongcheol ShinHyeongcheol commented Nov 12, 2025

문제

프로그래머스 - 가장 가까운 같은 글자

문제 설명

문자열 s가 주어졌을 때, s의 각 위치마다 자신보다 앞에 나왔으면서, 자신과 가장 가까운 곳에 있는 같은 글자의 위치

  • 앞에 같은 글자가 없다면 -1
  • 자신보다 n칸 앞에 같은 글자가 있다면 n으로 표현
  • 자신보다 n칸, n+2칸 앞에 있다면 n으로 더 가까운 값으로 표현

제한 사항

  • 1 <= s의 길이 <= 10000
  • s는 영어 소문자로만 구성

입출력 예시

s result
"banana" [-1,-1,-1,2,2,2]
"footbar" [-1,-1,1,-1,-1,-1]

기본 풀이

class Solution {
    fun solution(s: String): IntArray {
        var answer: IntArray = IntArray(s.length) {-1}
        for((index, text) in s.withIndex()){
            for(i in index - 1 downTo 0){
                if(text == s[i]){
                    answer[index] = index - i
                    break
                }
            }
        }
        return answer
    }
}

입력받은 문자열에 대해서 각 문자에 대해 반복하며 같은 문자의 index를 찾는 문제라고 생각하였습니다.

  1. 문자열을 -1로 초기화
  2. 문자열의 각 문자에 대해 반복
  3. 각 문자의 앞에 같은 문자가 있는지 탐색
  4. 있다면 index를 answer에 저장

심화 풀이

class Solution {
    fun solution(s: String): List<Int> {
        return s.withIndex().map { (i, c) -> s.slice(0 until i).lastIndexOf(c).let { if (it >= 0) i - it else -1 } }
    }
}
  1. 각 문자열의 인덱스와 값을 map의 형태로 변환하고, 결과를 list로 생성
  2. 현재 인덱스 이전의 값만 추출하고, 현재 문자가 마지막으로 나타난 인텍스를 탐색
  3. 있다면 인덱스간의 거리를 검색, 없다면 -1을 반환

위의 코드와 마찬가지로 반복문을 2번 거치기 때문에 O(n^2)의 수행시간을 가짐

class Solution {
    fun solution(s: String): IntArray {
        val answer = IntArray(s.length) {-1}
        val checkIndex = ('a'..'z').associate { it to -1 } as HashMap

        s.forEachIndexed { i, v ->
            if (checkIndex[v]!! > -1) answer[i] = (i - checkIndex[v]!!)
            checkIndex[v] = i
        }
        return answer
    }
}
  1. 문자열을 -1로 초기화
  2. 마지막 출현 인덱스를 추적하기 위한 a~z까지 소문자를 키로, -1을 값으로 가지는 해시맵을 생성
  3. 현재 문자 이전에 출현했는지 확인하고, 출현했다면 인덱스의 거리를 계산해 answer에 저장
  4. 현재 문자의 가장 최근 출현 인덱스를 현재 인덱스로 업데이트
  5. answer 결과 반환

이 과정의 경우 위의 2가지 방법과 다르게 미리 인덱스 맵을 준비하고, 맵의 인덱스를 조회하기 때문에 O(n)의 수행시간을 가짐

느낀점

처음에는 정말 단순하게 반복문만 잘 돌리고, 조건문만 잘 설정하면 가볍게 풀 수 있는 문제라고 생각했다.
첫주기도 하고 코틀린으로 알고리즘 문제를 푸는 것이 처음이라 가져오게 되었는데, 그래서 오히려 심화 풀이 부분이 더 신기하고 색다르게 느껴졌다.
어디에나 알고리즘 귀인들은 존재하는 것 같았다.

@ShinHyeongcheol ShinHyeongcheol changed the title [week1 신형철] - 가장 가까운 같은 글자 기본 풀이 [week1] - 가장 가까운 같은 글자 Nov 12, 2025
@ShinHyeongcheol ShinHyeongcheol changed the title [week1] - 가장 가까운 같은 글자 [week1] 가장 가까운 같은 글자 Nov 12, 2025
Copy link

@sonyerim sonyerim left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1주차 알콩달콩 수고하셨습니다 😎👍✨

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

-1 downTo 0 이면 마지막 인덱스부터 처음 인덱스까지 내림차순을 의미하는게 맞을까요?!

Copy link
Author

@ShinHyeongcheol ShinHyeongcheol Nov 12, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

요거 index-1 downTo 0 이라서 해당 인덱스의 앞부터 제일 앞까지에요!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants