LeetCode练习3:Longest Substring Without Repeating Characters

题目

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

Examples:

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

分析

题目的输入为:一个字符串 s s

题目输出为:字符串中不包含重复字符的最长子串的长度

该题目需要注意两点,一是原字符串的子串,二是子串内不包含重复元素。对于条件一的判断,我们可以对字符串从左向右扫描,保证子串中的字符是连续的,避免出现"pwwkew"中的情况;而为了判断是否存在重复字符,需要再加入新的字符时对其进行判断。

暴力解法是枚举出所有可能的子串,然后取长度最大的子串,但该做法的复杂度为O(n3),下面的解答则使用效率更高的方法。

解答

我们可以使用滑动窗口的方式记录最长的子串 sub s u b 。初始假设 j=i=0 j = i = 0 ,此时的窗口内的子串为 [i,j) [ i , j ) ,我们逐渐增加 j j ,当s[j]不在 sub s u b 中时,则将其添加到 sub s u b 中;反之,则找出 s[j] s [ j ] sub s u b 中的位置 idx i d x ,令 i=idx+1 i = i d x + 1 ,从而保证新的 [i,j) [ i , j ) 子串中不存在重复字符。

class Solution:
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        substring_list = []

        temp = ''
        for i in s:
            if i not in temp:
                temp += i
            else:
                substring_list.append(temp)
                idx = temp.index(i)
                temp = temp[idx+1:] + i

        substring_list.append(temp)
        max_substring_len = max([len(i) for i in substring_list])

        return max_substring_len

上述程序没有使用字典来记录字符的位置,而是直接利用了python中字符串内置函数index(),从而减少了复杂的程序编写。除此之外,程序首先将所有的子串(不包含重复字符)储存在substring_list中,然后找出最长子串的长度,从而便于程序的调试。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值