Example 1
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3
Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
제한사항
- 0 <= s.length <= 5 *
- s consists of English letters, digits, symbols and spaces.
결론은 알파벳이 중복되는 것 없는 최대 문자열 길이를 구하는 문제
제한상항 때문에 brute-force로하면 시간초과가 날 것 같다. 난이도가 좀 있는 문제다.
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
save = []
max_len = 0
for x in s:
if x in save:
save = save[save.index(x)+1:]
save.append(x)
max_len = max(max_len, len(save))
return max_len
한글자씩 확인하면서 이미 앞에서 나온 문자면 해당 위치 앞까지 문자열에서 자르고, 그렇지 않으면 문자열 뒤에 더합니다. 매 단계마다 max_len을 저장해줍니다.