leetcode #3

该博客介绍了LeetCode上的第3题,寻找给定字符串中最长的无重复字符的子串。提供了三种解决方案:暴力搜索、使用列表实现的滑动窗口以及利用哈希字典。并给出了每种方法的思路和代码实现。
摘要由CSDN通过智能技术生成

==============================================================================
【id】#3

【title】 Longest Substring Without Repeating Characters

【description】

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.

【idea】

  1. 暴力搜索

遍历字符串,找到第一个要比对的字符,然后遍历后边的子串,如果寻在重复字符,将比对位置+1;不存在记下最大长度。

【code】

class Solution:
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        start = 0
        max_len = 1
        if s == '': return 0
        while start < len(s):
            for i in range(start+1,len(s)):
                if s[i] not in s[start:i]:
                    max_len = max( max_len,i-start+1)
                    i += 1 
                else: break
            start +=1
        return max_len

【idea】
2. 列表表示的滑动窗口。
[i,j)为窗口,如果s[j] 不在窗口里边,j向右滑动,并记下最大长度;如果s[j]在窗口里,i向右滑动。

【code】

class Solution:
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        hashlist = []
        length = len(s)
        max_len = 0
        i = j = 0
        while i<length and j<length:
            if s[j] not in hashlist:
                hashlist.append(s[j])
                j += 1
                max_len = max(max_len, j-i)
            else:
                hashlist.remove(s[i])
                i += 1
            
        return max_len

【idea】

3.hash字典。
按照顺序遍历字符串,字典中存入{val:index}。
如果s[i]已经在字典中了,表示存在重复字段,那么开始位置移动到重复字段位置后即i+1。
如果不在字典中,表示不重复,记录下最大长度。

【code】

class Solution:
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        dic = {}
        start = 0
        max_len = 0
        for i in range(len(s)):
            if s[i] in dic and start <= dic[s[i]]:
                start = dic[s[i]] + 1
            else:
                max_len = max(max_len,i-start+1)
            dic[s[i]] = i
        return max_len
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值