Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 개발자 취업
- 단기개발자코스
- 개발자부트캠프추천
- jwt
- 빈 조회 2개 이상
- TiL
- 파이썬
- 구글 OAuth login
- 프로그래머스
- 커스텀 헤더
- DesignPattern
- Spring multimodule
- 빈 충돌
- 디자인 패턴
- 취업리부트코스
- 전략패턴 #StrategyPattern #디자인패턴
- jwttoken
- 99클럽
- 디자인패턴
- 프로그래머스 이중우선순위큐
- spring batch 5.0
- @FeignClient
- 1주일회고
- 항해99
- 인프콘 2024
- KPT회고
- infcon 2024
- JavaScript
- Python
- 코딩테스트 준비
Archives
- Today
- Total
m1ndy5's coding blog
LeetCode 3. Longest Substring Without Repeating Characters with Python 본문
알고리즘 with python/알고리즘 스터디
LeetCode 3. Longest Substring Without Repeating Characters with Python
정민됴 2024. 1. 4. 20:03[https://leetcode.com/problems/longest-substring-without-repeating-characters/]
내가 푼 코드
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
answer = 0
# 중복 알바벳 체크
alpha = set()
# 길이가 1이면 그냥 1 리턴
if len(s) == 1:
return 1
for i in range(len(s) - 1):
alpha = set()
# 차례대로 비교해서 중복 있으면 포문 나오기
for j in range(i, len(s)):
if s[j] not in alpha:
alpha.add(s[j])
else:
break
# 현재 최대값이랑 비교해서 더 큰걸로 바꾸기
answer = max(len(alpha), answer)
return answer
통과되긴 했지만 사실 포문을 돌면서 계속 set을 초기화하는 것과 이중포문을 쓰는 것이 별로 맘에 들진 않았던 코드였다.
책코드
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
used = {}
max_length = start = 0
for i, v in enumerate(s):
# 이미 등장했던 문자라면 start 위치 갱신
if v in used and start <= used[v]:
start = used[v] + 1
else:
max_length = max(max_length, i-start+1)
# 현재 문자의 위치 삽입
used[v] = i
return max_length
인덱스와 값을 사용해서 이미 등장했던 문자라면 start를 다음 위치로 옮겨주고 계속해서 max길이를 갱신하는 방법이다.
set을 계속 재정의할 필요도 없고 포문도 한번만 돌면되서 훨씬 효율적인 코드였다.
다음부터 인덱스와 값을 적절히 사용해서 문제를 풀도록 노력해봐야겠다.
'알고리즘 with python > 알고리즘 스터디' 카테고리의 다른 글
LeetCode 1464. Maximum Product of Two Elements in an Array with Python (0) | 2024.01.05 |
---|---|
LeetCode 347. Top K Frequent Elements with Python (0) | 2024.01.04 |
LeetCode 771. Jewels and Stones with Python (1) | 2024.01.04 |
LeetCode 739. Daily Temperatures with Python (1) | 2024.01.04 |
LeetCode 232. Implement Queue using Stacks with Python (0) | 2024.01.04 |