首页 > 试题广场 >

最长不含重复字符的子字符串。

[编程题]最长不含重复字符的子字符串。
  • 热度指数:447 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解


请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。

示例1

输入

"abcabcbb"

输出

3

说明

因为无重复字符的最长子串是"abc",所以其长度为 3
示例2

输入

"pwwkew"

输出

3

说明

因为无重复字符的最长子串是 "wke",所以其长度为 3。
     请注意,你的答案必须是子串的长度,"pwke" 是一个子序列,不是子串。
示例3

输入

"ipalfish"

输出

7

说明

因为无重复字符的最长子串是"palfish",所以其长度为 7。
哈希表+双指针滑动窗口。时间复杂度o(n),只遍历一次;空间复杂度o(1),虽然用了哈希表,但是字符ASCII码0~127,也就是说哈希表最多存128个数据,这是个常数级别,可认为是o(1)。
function lengthOfLongestSubstring( s ) {
    // write code here
    //1. 用一个map存储子字符串信息,key-字符,value-下标。
    //2. 滑动窗口,双指针,begin,end。再用一个变量maxLength记录最大长度。
    //3. end变量字符串,如果map中有重复字符,maxLength = max(maxLength,
    // end-begin),更新begin = max(begin, value+1)。
    //4. 更新map信息。
    //5. 最后再更新一次maxLength。
    const map = new Map();
    let begin = 0;
    let end = 0;
    let maxLength = 0;
    while (end < s.length) {
        const char = s.charAt(end);
        if (map.has(char)) {
            maxLength = Math.max(maxLength, end - begin);
            begin = Math.max(begin, map.get(char) + 1);
        }
        map.set(char, end);
        end++;
    }
    maxLength = Math.max(maxLength, end - begin);
    return maxLength;
}


发表于 2021-08-13 11:51:56 回复(0)
#

# @param s string字符串 
# @return int整型
#
from collections import defaultdict
class Solution:
    def lengthOfLongestSubstring(self , s ):
        # write code herekm 
        window = dict.fromkeys(s, 0)
        left = 0
        right = 0
        res = 0
        while right < len(s):
            c = s[right]
            right += 1
            window[c] += 1
            while window[c]>1:
                d = s[left]
                left += 1
                window[d] -= 1
            res = max(res, right-left)
        return res
发表于 2023-11-14 16:21:28 回复(0)
#
# 
# @param s string字符串 
# @return int整型
#
from collections import defaultdict
class Solution:
    def lengthOfLongestSubstring(self , s ):
        # write code herekm 
        window = dict.fromkeys(s, 0)
        left = 0
        right = 0
        res = 0
        while right < len(s):
            c = s[right]
            right += 1
            window[c] += 1
            while window[c]>1:
                d = s[left]
                left += 1
                window[d] -= 1
            res = max(res, right-left)
        return res

发表于 2022-10-23 17:49:22 回复(0)