您的位置:首页 > 编程语言 > Python开发

LeetCode 3. Longest Substring Without Repeating Characters---Python实现

2018-01-29 01:53 483 查看
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.

题意很明白,在一个字符串中找一个最长的不重复连续字串,选用一个字典来存储每个字符的位置,进行遍历即可。具体代码分析如下。class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        usechar={}
        start=length=0 # /length=i=0
        for i in range(len(s)):  # for i in len(s):
            if s[i] in usechar and start <=usechar[s[i]]:  # if s[i] in usechar and start<=s[i]:
                start=usechar[s[i]]+1# start=s[i]+1 #直接从重复的之后再来算啊。usechar里面的都是唯一的啊。
            else:
                length=max(length,i-start+1)
            usechar[s[i]]=i;
        return length
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐