码迷,mamicode.com
首页 > 编程语言 > 详细

Leetcode Longest Substring Without Repeating Characters python

时间:2014-09-22 23:29:43      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   os   ar   for   div   sp   

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 one
11             tmp=""
12             max_len=0
13             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                 pass
28             return max_len

 

Leetcode Longest Substring Without Repeating Characters python

标签:style   blog   color   io   os   ar   for   div   sp   

原文地址:http://www.cnblogs.com/echo-lsh/p/3986829.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!