Given a string s, find the length of the longest substring without repeating characters.
풀이
1.
처음엔 단순하게 중복문자가 나온다면 중복 문자를 넣고 초기화 하는 방법으로 했는데
실패했다 , 문제에서 요구하는 바는 중복되는 '문자열'을 확인해야했다.
2.
슬라이딩 윈도우로 for문을 돌면서 중복되는 문자열이 나온다면
result 리스트안의 문자가 겹치는 부분을 슬라이싱을 통해서 뗴낸 후 다시 for문을 넣는 방법을 생각했지만
인덱싱 슬라이스를 하며 초기화 되는부분을 상세하게 넣지 못해서 계속 실패했다.
1.
class Solution(object):
def lengthOfLongestSubstring(self, s):
counter =0
result =[]
for i in range(len(s)):
if s[i] not in result:
result.append(s[i])
else:
result =[s[i]]
counter= max(counter,len(result))
return counter
"dvdf" vdf
2.
counter =0
result =[]
for i in range(len(s)):
if s[i] not in result:
result.append(s[i])
else:
for j in range(len(result)):
if s[i] == result[j]:
result =result[j:]
print(result)
break
# print(result)
counter= max(counter,len(result))
이후에 솔루션을 찾아보니 비슷한 방법으로 푼 사람의 코드를 보니
내 코드는
중복되는 문자열을 발견했을 때 인덱스 슬라이싱을 한 후 result문자열에 넣는 방법이 잘못되었다는걸 깨달았다.
# result =""
# max_length = 0
# for i in s:
# if i in result:
# result = result[result.index(i)+1:]
# """if abcdas is the string, here after abcd the length would be 4 and result will be replaced as bcda"""
# result += i
# max_length = max(max_length, len(result))
# return (max_length)
아직도 어지럽다..ㅋㅋㅋ 비슷한 문제를 다시 풀어봐야지 익숙해질것같다.
'알고리즘 > LeetCode' 카테고리의 다른 글
LeetCode 141. Linked List Cycle (0) | 2023.08.29 |
---|---|
LeetCode 209. Minimum Size Subarray Sum (0) | 2023.08.29 |
LeetCode 167. Two Sum II - Input Array Is Sorted (0) | 2023.08.28 |
LeetCode 125. Valid Palindrome (0) | 2023.08.27 |
LeetCode 55. Jump Game (0) | 2023.08.25 |