==============================================================================
【id】#3
【title】 Longest Substring Without Repeating Characters
【description】
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.
【idea】
- 暴力搜索
遍历字符串,找到第一个要比对的字符,然后遍历后边的子串,如果寻在重复字符,将比对位置+1;不存在记下最大长度。
【code】
class Solution:
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
start = 0
max_len = 1
if s == '': return 0
while start < len(s):
for i in range(start+1,len(s)):
if s[i] not in s[start:i]:
max_len = max( max_len,i-start+1)
i += 1
else: break
start +=1
return max_len
【idea】
2. 列表表示的滑动窗口。
[i,j)为窗口,如果s[j] 不在窗口里边,j向右滑动,并记下最大长度;如果s[j]在窗口里,i向右滑动。
【code】
class Solution:
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
hashlist = []
length = len(s)
max_len = 0
i = j = 0
while i<length and j<length:
if s[j] not in hashlist:
hashlist.append(s[j])
j += 1
max_len = max(max_len, j-i)
else:
hashlist.remove(s[i])
i += 1
return max_len
【idea】
3.hash字典。
按照顺序遍历字符串,字典中存入{val:index}。
如果s[i]已经在字典中了,表示存在重复字段,那么开始位置移动到重复字段位置后即i+1。
如果不在字典中,表示不重复,记录下最大长度。
【code】
class Solution:
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
dic = {}
start = 0
max_len = 0
for i in range(len(s)):
if s[i] in dic and start <= dic[s[i]]:
start = dic[s[i]] + 1
else:
max_len = max(max_len,i-start+1)
dic[s[i]] = i
return max_len