Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", 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.
Solution1
此方法容易想到,遍历整个字符串,子串用两层的嵌套循环来滑动;
一旦,子串被check出有重复的字符,切到下一个子串进行check。
其中,子串的最大值用一个变量来保存,此变量每次都跟当前check的子串的长度compare
其中,查重用到了set(hash查找效率快)
注意: 此算法的复杂度非常高,O(n3)
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
maxl = 0
for i in range(len(s)):
for j in range(i, len(s) + 1):
if self.unique(s[i:j]):
maxl = max(maxl, j - i)
else:
break
return maxl
def unique(self, astr):
aset = set()
for s in astr:
if s not in aset:
aset.add(s)
else:
return False
return True
solution2
同样是遍历整个字串,但是会将每个字符都按照顺序放在一个map中。
一旦check到某个字符曾经在map中出现于pos,子串的长度则从pos + 1开始重新计算。
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
amap = {}
start = maxl = 0
for i in range(len(s)):
#print start, amap
if s[i] in amap and start <= amap[s[i]]:
start = amap[s[i]] + 1
else:
maxl = max(maxl, i - start + 1)
amap[s[i]] = i
return maxl
注意: 以上的算法,start <= amap[s[i]]一定不能够漏掉。不然start就会回退。
此算法,只遍历一次字符串,search的动作使用到map,因此算法的复杂度为O(n)