Skip to content

[Algorithm] 가장 가까운 같은 글자 #35

@hwangJi-dev

Description

@hwangJi-dev

💬 문제

[코딩테스트 연습 - 가장 가까운 같은 글자](https://school.programmers.co.kr/learn/courses/30/lessons/142086)

💬 Idea

  1. dict에 글자의 지난 index를 저장해두고 해당 글자가 다시 나오면 최신 index에서 지난 index를 빼서 index의 차이를 구하자.

💬 풀이

func solution(_ s:String) -> [Int] {
    var wordIndexDict: [String: Int] = [:]
    var result: [Int] = []
    
    for (index, i) in s.enumerated() {
        let word = String(i)
        
        if wordIndexDict[word] != nil {
            result.append(index - wordIndexDict[word]!)
        } else {
            result.append(-1)
        }
        
        wordIndexDict[word] = index
    }
    
    return result
}

Metadata

Metadata

Assignees

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions