[Leetcode_PY]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.

思路

最长非重复字符的字串。

扫描第一遍
记录子字符串的开头和结尾,
结尾先移动尾巴,一边移动,一边统计字串的,各字符的数量
(需要一个辅助字典或者数组,py字典方便啊)
一旦出现某个字符重复出现
则头指针右移,直到重复消除为止。
(注意统计字符串,相应的字符要减一)
尾指针正常到结尾,就结束了。

用两个变量来存结果,maxlen,maxlen_head。
每次正常移动的时候,如果比上次结果好,就存下来。

只需要长度,就不记录maxlen_head了。
另外当结尾指针越过边界时,停止就好了,头指针再右移也不会找到更长的了。

代码

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        char_dict = {}
        s_len = len(s)
        if len(s_len) == 0:
            return 0
        if len(s_len) == 1:
            return 1
        head = 0
        tail = 0
        max_sublen = 1
        while tail <= s_len - 1:
            if s[tail] not in char_dict or char_dict[s[tail]] == 0:
                char_dict[s[tail]] = 1
                current_len = tail - head + 1
                if current_len > max_sublen:
                    max_sublen = current_len
            else:
                char_dict[s[tail]] += 1
                while head < tail:                    
                    char_dict[s[head]] -= 1
                    head += 1
                    if char_dict[s[tail]] == 1:
                        break
            tail += 1

        return max_sublen
posted @ 2016-01-20 15:55  程序员杰诺斯  阅读(121)  评论(0编辑  收藏  举报