Leetcode题目之最长无重复子串

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36470920/article/details/88598171

先来看问题描述:

Given a string, find the length of the longest substring without repeating characters.

给一个字符串,找出来这个字符串中最长的没有重复字符的子串

Example 1:

Input: "abcabcbb"
Output: 3 
Explanation: The answer is "abc" with the length of 3

Example 2:

Input: "bbbbb"
Output: 1
Explanation: The answer is "b" with the length of 1

Example 3:

Input: "pwwkew"
Output: 3
Explanation: The answer is "wke" with the length of 3

其实题目还是挺好懂,然后接下来说下我的想法:首先采用遍历的思想,每次输入进来一个字符串,逐个地去分析这个字符串的字符,并将其添加进去一个对比列表中,然后继续读取下一个字符,当发现这个字符不在对比列表中,说明这个字符和列表里面的字符都不一样,那就说明目前的字符串是没有重复的子串,因此将这个字符添加进去,然后返回目前的对比列表的长度,来表示当前的子串长度;当遍历到一个字符发现它已经存在于列表中,此时应该找出来这个在列表中已经存在的字符,它的下标,然后将这个下标之前的字符全部删除掉,因为这样才能保证子字符串没有重复的字符。注意,每处理一个字符都要进行判断和返回数组长度的操作(其实这步可以优化,比如发现有重复字符了,很显然字符串长度只可能减少不可能增加的,但是为了简短起见,我没有处理优化)。

接下来是我的代码:python3.5

# Author:Yuan Tian
# Date:2019/3/16
class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        list = []
        num = []
        for i in s:
            if i not in list:
                list.append(i)
                # print(list)
                num.append(len(list))
                # print(num)
                continue
            if i in list:
                j = list.index(i)
                list = list[j+1:]
                list.append(i)
                # print(list)
                num.append(len(list))
                # print(num)
        return 0 if len(num)==0 else max(num)

注意字符串为0的特殊情况。

最终提交完成,谢谢!

猜你喜欢

转载自blog.csdn.net/qq_36470920/article/details/88598171