1. 题目
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.
2. 题目理解
输入一个字符串,输出该字符串中最长不重复子串的字符数。
3. 代码实现
1)思路一
将本位存到字符表中,判断下一位字符是否存在于字符表相同:若不同,temp+1,并加入字符表;若相同,temp_max为当前最长字符数,清空字符表,并从下一位开始判断。但存入字符表再进行字符表的匹配会造成一些冗余。
2)思路二
构建字典dict,起始位start,长度最大值maxl。若字典中存在当位且字典中存储的值+1大于起始位的值,起始位改为当前位+1。将当前位更新到字典中,并将当前最长不重复字符数maxl更新为当前位-start+1与当前maxl中的较大值。
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
start = 0
maxl = 0
dict = {}
for i, value in enumerate(s):
if s[i] in dict and dict[value]+1 > start:
start = dict[value] + 1
dict[value] = i
maxl = max(i-start+1, maxl)
return maxl