Longest Substring Without Repeating Characters

Tasic·2021년 1월 24일
0

Algorithm

목록 보기
3/4

Question

링크
주어진 문자열에서 문자가 중복되지 않으면서 연속된 문자열의 최대 길이를 구한다.

Code

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        longestStrLen = 0
        startIdx = 0
        existStr = set()
        i = 0
        
        while i < len(s) :
            #해당 문자가 중복되지 않으면 문자열 추가 후 다음문자 검사
            if s[i] not in existStr :
                existStr.add(s[i])
                i+=1
            else :
            #해당 문자가 중복되는 경우 지금까지 검색한 문자의 길이를 측정 후, 길이가 가장 길 시 값 업데이트
                tmpLen = len(existStr)
                longestStrLen =  longestStrLen > tmpLen and longestStrLen or tmpLen 
                # 검색한 문자열 초기화
                existStr.clear()
                # 검사 시작 위치 변경
                startIdx+=1
                i = startIdx
                

	#마지막까지 검색한 문자열에 대해서 동일 작업 진행
        tmpLen = len(existStr)
        longestStrLen =  longestStrLen > tmpLen and longestStrLen or tmpLen 
        return longestStrLen

Result

수정하고 싶은 사항

로직은 이중 for문 느낌인데, 다른 방법이 있을테니 이중 for문 안쓰고 할 수 있도록 변경하고 싶음.

profile
블로그 옮겼습니다 (https://jotasic.github.io)

0개의 댓글