3. Longest Substring Without Repeating Characters
Medium
13757711Add to ListShare
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 "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.
Example 4:
Input: s = ""
Output: 0
Constraints:
0 <= s.length <= 5 * 104
s
consists of English letters, digits, symbols and spaces.
我的提交:
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
"""
思路:从下标0开始枚举字符保存到字符串里,直到找到一个字符在之前的字符串里出现过,
更新最长子串长度,然后从之前出现过得字符下标的下一位开始枚举,因为之前的必不可能比当前已知的更长
时间并没达到O(n),与str.find的查找时间有关
如:abcabcbb
abc[a]
bca[b]
cab[c]
abc[b]
cb[b]
"""
max_len = 1
left, right = 0, 1
while left < len(s):
if right >= len(s):
return max(max_len, right - left)
c = s[right]
sub_string = s[left: right]
if c in sub_string:
index = sub_string.find(c)
max_len = max(max_len, right - left)
left += index + 1
right = left + 1
continue
right += 1
return 0
标准答案思路:滑动窗口,维护左右下标并标记字符出现的次数,时间O(2n)=O(n)
Java:
public class Solution {
public int lengthOfLongestSubstring(String s) {
int[] chars = new int[128];
int left = 0;
int right = 0;
int res = 0;
while (right < s.length()) {
char r = s.charAt(right);
chars[r]++;
while (chars[r] > 1) {
char l = s.charAt(left);
chars[l]--;
left++;
}
res = Math.max(res, right - left + 1);
right++;
}
return res;
}
}
python:
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
chars = [0] * 128
left = right = 0
res = 0
while right < len(s):
r = s[right]
chars[ord(r)] += 1
while chars[ord(r)] > 1:
l = s[left]
chars[ord(l)] -= 1
left += 1
res = max(res, right - left + 1)
right += 1
return res