【leetcode】Longest Substring Without Repeating Characters

题目描述:

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.

解题思路:

暴力方法不谈。学到了一种O(n)的方法,思想也是两个指针(我自己开始的AC代码考虑的是不匹配的回退值,不仅麻烦而且通用性还不够好)。首先我们用left和right分别表示满足题目的序列的两端下标,那么我们可以想到,首先在该值不重复的时候不断移动right指针,当遇到重复时我们则要比较是否满足最长,另外要移动left找到最佳的重新开始长度,这个长度就是使得新加入的right不是重复的。

class Solution:
    # @return an integer
    def lengthOfLongestSubstring(self, s):
        left =0 
        right = 0
        res = 0
        lis = [] 
        l = len(s)
        while right < l:
            if s[right] in lis:
                if res < right - left:
                    res = right - left
                while s[left] != s[right]:
                    lis.remove(s[left])
                    left += 1
                left += 1
            else:
                lis.append(s[right])
            right += 1
        if res < right - left:
            res = right - left
        return res
posted @ 2015-01-22 17:02  mrbean  阅读(210)  评论(0编辑  收藏  举报