Given "abcabcbb"
, the answer is "abc".
分析:
根据子串的结构, 循环遍历原始串str, 保存非重复且当前长度最长的子串new_str.
例如, 当指针指向str的 i 位置, 判断当前位置的字符是否在new_str中出现过,若没有,当前new_str长度加一,并将i位置的字符放入new_str中,
如若有, new_str中出现该字符的位置以后的子串作为新子串new_str, 同样将i位置的字符加入new_str, 直到结束.
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
new_str = ''
max = 0
for ch in s:
if not ch in new_str:
new_str += ch
else:
max = len(new_str) if len(new_str) > max else max
idx = new_str.find(ch)
new_str = new_str[idx+1:] + ch
max = len(new_str) if len(new_str) > max else max
return max