3. Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3.Example 2:
Input: "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1.Example 3:
Input: "pwwkew" Output: 3 Explanation: The answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
双指针,滑动窗口
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
if not s:
return 0
else:
res = 1
# two pointers
left = 0
right = 1
for i in range(len(s)-1):
if s[right] not in s[left:right]:
res = max([right-left+1, res])
right = right + 1
else:
left = left + 1
while s[right] in s[left:right]:
left = left + 1
right = right + 1
return res
来源:CSDN
作者:authorized_keys
链接:https://blog.csdn.net/authorized_keys/article/details/103977077