一、题目
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.
二、思路
从左往右依次遍历字符串s,如果不在子串substr中,则加入,如果item在substr中,首先判断目前的子字符串的长度是否为当前最长,然后我们思考下一个子字符串应该是从重复的这个字符的下一个开始的,因为如果在这个字符之前那么必然还是会遇见重复的item的。全部遍历后 判断当前长度是否为最长。
遍历字符串每个字符:
若字符不在子串substr中:
substr加入此字符;
若字符在子串substr中:
if 当前 substr 当前子字符串最长:
当前的字符串长度付给变量 longestlenth
else(当前的子字符串 substr 并不是最长):
当前项item加入到substr中
并且删除当前子串中第一次重复出现的字符,从此字符的一下位开始
循环遍历到最后,若len(substr) > longestlenth,则:
longestlenth = len(substr)
return longestlenth
#coding:utf-8 def lengthOfLongestSubstring(s): """ :type s: str :rtype: int """ # s为空的情况 if not s: return 0 longestlenth = 1 # 非空子字符串的长度最小为1 substr = "" # 子字符串 for item in s: if item not in substr: substr += item else: if len(substr) > longestlenth: longestlenth = len(substr) # 应该从重复的下一个字符开始继续判断 substr += item substr = substr[substr.index(item)+1:] if len(substr) > longestlenth: longestlenth = len(substr) return longestlenth """ :type s: str :rtype: int maxlength = 0 length = 0 substring = [] for i in s: try: index = substring.index(i) substring = substring[index+1:] substring.append(i) maxlength = max(maxlength, length) length = length - index except ValueError: substring.append(i) length += 1 maxlength = max(maxlength, length) return maxlength """ if __name__ == '__main__': print(lengthOfLongestSubstring("abcabcbb"))
(来源:http://blog.csdn.net/iwanthn/article/details/54670292#t5)