Leetcodeleetcode

3. Longest Substring Without Rep

2017-10-26  本文已影响1人  ciantian

最近再刷leetcode,除了链表之外的都用python 实现,贴出一些代码,希望指正.

问题描述:

Given a string, find the length of the longest substring without repeating characters.
给定一个字符串,找到其中没有相同字符的最长序列.

样例输入:

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.

解决方案.

采用插入的思想.用一个list来暂存数据.遍历整个字符串,每拿到一个字符串先再暂存的list中找,看有没有出现过,若出现则把相同字符串之前的全删除,把这个字符,再填如.
用 abcabcbb做示范
list = []
遍历a,因为list是空,所以直接把a放入list,list = [a] len = 1
遍历b,list中没有b,所以b进入,list = [a,b] len = 2
遍历c,list中没有c,所以c进入,list = [a,b,c] len = 3
遍历a,list中有a,则删除a之前的字符再把a插入,list = [b,c,a] len = 3
....
同理,遍历完之后获得最大的len.

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        list_new = []
        def dele_same_char(list_new, same_char_index):
            return list_new[same_char_index+1:]
        def find_same_char(list_new, char):
            if len(list_new) == 0:
                return -1
            for i, each in enumerate(list_new):
                if each == char:
                    return i
            return -1
        max = 0
        for i, char in enumerate(s):
            # 1.找形同的位置
            same_char_index = find_same_char(list_new, char)
            if same_char_index != -1:
                # 说明存在
                # 2.删相同的之前的元素
                list_new = dele_same_char(list_new, same_char_index)
            list_new.append(char)
            # 3.求长度
            length = len(list_new)
            if length > max:
                max = length
        return max
solution = Solution()
print(solution.lengthOfLongestSubstring("abcabcbb"))
上一篇下一篇

猜你喜欢

热点阅读