首页 > 代码库 > Leetcode Longest Substring Without Repeating Characters python

Leetcode Longest Substring Without Repeating Characters python

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

 

解题思路:利用find函数寻找在字串中是否已经存在要查找的字母,如果存在,则选择从字串中要查找字母的下一个字母重新计数新的字串,当然在这的时候要判断已经寻找的字串是否比现存的字串长。同时要注意处理最后的查找出的字串。

eg:s="echocomeon",以查找到字串tmp=“echoc”,当查找s[5]=‘o‘时,在字串tmp中已经存在‘o’,检查len(tmp)与已经存在字串的长度大小,同时更新新的字串tmp=“co”。

 1 class Solution: 2     # @return an integer 3     def lengthOfLongestSubstring(self, s): 4         length=len(s) 5         if (length==0): 6             return 0 7         elif(length==1): 8             return 1 9         else:10             #work with the data one by one11             tmp=""12             max_len=013             str_len=""14             for i in range(length):15                 index=tmp.find(s[i])16                 if(index>-1):17                     if(len(tmp)<max_len):18                         tmp=tmp[(index+1):]+s[i]19                     else:20                         max_len=len(tmp)21                         tmp=tmp[(index+1):]+s[i]22                 else:23                     tmp=tmp+s[i]24             if(len(tmp)>max_len):25                 max_len=len(tmp)26             else:27                 pass28             return max_len

 

Leetcode Longest Substring Without Repeating Characters python