Leetcode 3. Longest Substring Without Repeating Characters

Leetcode 3. Longest Substring Without Repeating Characters

题目说明

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.
Note that the answer must be a substring, “pwke” is a subsequence and not a substring.

代码部分1

class Solution:
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        L = list()
        M = list()
        if s == '':
            M.append(0)
        elif len(s) == 1:
            M.append(1)
        else:
            ss = ''
            for i in range(len(s)):
                ss = s[i:]
                for i in ss:
                    if i in L:                
                        M.append(len(L))
                        L = list()
                        break
                    else:
                        L.append(i)
        return max(M)

结果:超时

主要思路:
1.从左开始依次读取剩下的字符串作为子串
2.以每一个子串为研究目标,寻找每一个子串中无重复字符的子子串的最大长度
3.输出所有子串中最大值
4.对于空串以及单个字符串采取分类讨论这种最原始的解法
评价:
思路清晰,方法简单但耗时耗资源

代码部分2

class Solution:
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        L = list()
        M = 0
	    for i in s:
	         if i in L:
	             M = max(M,len(L))
	             while i in L:
	                 del L[0]
	             L.append(i)
	         else:
	             L.append(i)
        M = max(M,len(L))
        return max(M)

结果:Runtime: 116 ms, faster than 50.80% of Python3

主要思路:
1.L作为子串,类型为列表,可通过del和append来增加和删减
2.for i in s,当i没有在子串L中出现过,则append
3.若i在L中出现过,则记录下此时的L长度并从左del子串L中值直至i不在L中
4.输出返回M中的最大值
评价:
子串L重复利用,节省空间
此方法解决了s为1的例子

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值