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 | 29 | 30 |
Tags
- 판다스
- pandas
- Til
- 파이썬
- 유데미코리아
- 데이터드리븐
- 시각화
- 데이터분석
- numpy
- ndarray
- python
- 코딩테스트
- 유데미
- 부트캠프후기
- matplotlb
- 브루트포스 알고리즘
- 유데미부트캠프
- 스타터스부트캠프
- Leetcode
- 백준
- 유데미큐레이션
- 데이터시각화
- 넘파이
- 데이터프레임
- 취업부트캠프
- Tableau
- 정렬
- DataFrame
- 그리디 알고리즘
- 태블로
Archives
- Today
- Total
Diary, Data, IT
[LeetCode] 3. Longest Substring Without Repeating Characters - Python 본문
Coding Test/LeetCode
[LeetCode] 3. Longest Substring Without Repeating Characters - Python
라딘 2023. 4. 14. 14:08[LeetCode] 3. Longest Substring Without Repeating Characters - Python
Longest Substring Without Repeating Characters - LeetCode
Can you solve this real interview question? Longest Substring Without Repeating Characters - Given a string s, find the length of the longest substring without repeating characters. Example 1: Input: s = "abcabcbb" Output: 3 Explanation: The answer is "
leetcode.com
문제
문자열 s가 주어질 때, 중복되는 문자가 없는 가장 긴 문자열의 길이를 반환하세요.
예를 들어 s = "abcabcbb" 라면, 중복되지 않는 가장 긴 문자열은 "abc"이므로 3을 반환합니다.
아이디어
1) 먼저, 중복 문자인지를 판별하기 위한 딕셔너리를 만든다.
2) 문자를 차례대로 탐색하면서 현재 문자가 이미 등장했는지 판별하고, 등장했다면 그 문자가 처음 등장한 위치 + 1로 이동해서 다시 시작한다.
3) 현재 문자가 아직까지 나오지 않았으면 문자열 길이를 저장하는 변수에 1을 더해준다.
코드
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
used = {};
max_length = 0;
start = 0
for idx, char in enumerate(s):
if char in used and start <= used[char]: # 같은 문자열이 2번째 등장한 경우
start = used[char] + 1 #첫번째 등장한 지점 이후로 start 갱신
else: # 빈 경우, 아직 등장하지 않은 경우, start 이후 1번만 등장한 경우
max_length = max(max_length, idx - start + 1)
used[char] = idx # 현재 등장한 위치로 갱신
# 여기서 갱신해줘야 2번째 나왔을 때 찾게됨(start보다 idx가 크기때문에)
return max_length
'Coding Test > LeetCode' 카테고리의 다른 글
[LeetCode] 17. Letter Combinations of a Phone Number - Python (0) | 2023.04.15 |
---|---|
[LeetCode] 200. Number of Islands - Python (0) | 2023.04.15 |
[LeetCode] 937. Reorder Data in Log Files - Python (0) | 2023.04.11 |
[LeetCode] 819. Most Common Word - Python (0) | 2023.04.11 |
[LeetCode] 344. Reverse String - Python (0) | 2023.04.11 |