Notice
Recent Posts
Recent Comments
Link
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Archives
Today
Total
관리 메뉴

JustDoEat

[Python/String-Manipulation]Length of Longest Substring without Repetition 본문

카테고리 없음

[Python/String-Manipulation]Length of Longest Substring without Repetition

kingmusung 2023. 11. 26. 19:47

문제

주어진 문자열에서, 가장 긴 반복된 문자가 없는 substring의 길이를 구하시오.

 

입출력 예시1:

Input: str = “Appleismyfavorite”

Output: 12. (pleismyfavor)

코드

str = 'Appleismyfavorite'
str_list = list(str) # 입력받은 문자열을 리스트로 변환하여 저장.
str_string="" 
result_list=[[]] # 서브 스트링을 리스트 안 리스트로 저장.
str_dic={} 
i=0

while i < len(str_list):          #for i in range(len(str_list)) :
   if str_list[i] in str_dic: # 인덱스에서 가지고온 문자가 딕션어리에 있으면, 중복됨으로 조건에 부합x
      result_list.append(list(str_string)) #else문에서 조합한 문자열을 리스트안에 리스트에 넣어주고
      i = str_dic[str_list[i]]+1 # str_list[i]를 키값에 넣으면 중복이 되었던 문자의 인덱스 번호(i)가 나오고 그 뒤부터 이어가야 함으로 +1을 해줌.
      str_string = "" # 다음 substring을 만들어야 하므로 str_string은 다시 초기화
      str_dic={} #딕션어리도 위와 같은 이유로 초기화
   else:
      str_string+=str_list[i] #인덱스에서 가져온 문자가 딕션어리에 없으면 한글짜식 문자열로 만들고
      str_dic[str_list[i]]=i #알파벳과 알파벳 인덱스 위치를 딕션어리에 저장.
      i +=1 # i 를 올려줌으로 다음 인덱스를 가르키게 만들어줌
result_list.append(list(str_string)) #마지막 문자열 추가해주기.


max=-1 #이중리스트 안에서 가장긴 부분을 찾고
result_str='' #그부분을 문자열로 땡겨옴

for item in result_list: 
   if len(item)>=max:
      max=len(item)
      result_str=''.join(item)

print(result_str)

    


'''Apaleismyfavorite

    ap
    paleismyf
    leismyfavor
    sm

    패턴을 보면 겹치는 문자 바로 앞부터 루프가 돌아야하니까 각 알파벳 위치를 딕션어리에 저장.
'''