문제

142086

아이디어

  1. 얼만큼 반복해야 하는가? → s의 길이만큼 반복된 result 가 나와야 함 ⇒ range(len(s))
  2. temp라는 변수에 중복되지 않은 문자열을 담음
  3. 이후에 해당하는 문자열이 temp라는 변수에 존재하지 않는다면→ -1 반환
  4. 이미 s[i]라는 문자열이 temp 배열안에 존재한다면
    1. 해당 인덱스에서 마지막 인덱스 값을 뺀 만큼 answer 배열에 추가하여 인덱스 차를 더함
    2. 그리고 마지막 인덱스 값을 최신값인 i로 업데이트

코드

def solution(s):
    answer = []
    temp = []
    last_index = {}
    #얼마나 반복할 것인가? -> s의 글자만큼

    for i in range(len(s)):
        if s[i] not in temp:
            temp.append(s[i])
            answer.append(-1)
            
        #s[i]이 이미 나온경우
        else:
            answer.append(i - last_index[s[i]])
        
        **last_index[s[i]] = i**

    return answer