2021-01-04 LeetCode无重复字符的最长子串

题目要求

给定一个字符串,请你找出其中不含有重复字符的最长子串的长度。

示例输入 & 输出 & 解释
示例1输入: s = "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3
示例2输入: s = "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 “b”,所以其长度为 1
示例3输入: s = "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 “wke”,所以其长度为 3
请注意,你的答案必须是 子串 的长度,“pwke” 是一个子序列,不是子串
示例4输入: s = ""
输出: 0
示例5输入:nums1 = [2], nums2 = []
输出:2.00000
提示0 <= s.length <= 5 * 104
s 由英文字母、数字、符号和空格组成

JavaScript代码

var lengthOfLongestSubstring = function(s) {
    if (s.length <= 1) {
        return s.length;
    }
    let maxLength = 0;
    let startIndex = 0;
    let endIndex = 1;
    let theChars = new Map();
    theChars.set(s.slice(startIndex, startIndex + 1), startIndex);
    while (startIndex != s.length - 1 && endIndex < s.length) {
        if (!theChars.has(s.slice(endIndex, endIndex + 1))) {
            theChars.set(s.slice(endIndex, endIndex + 1), endIndex);
            endIndex += 1;
        } else {
            if (maxLength < theChars.size) {
                maxLength = theChars.size;
            }
            theChars.clear();
            startIndex += 1;
            theChars.set(s.slice(startIndex, startIndex + 1), startIndex);
            endIndex = startIndex + 1;
        }
    }
    if (theChars.size != 0) {
        if (maxLength < theChars.size) {
            maxLength = theChars.size;
        } 
    }
    return maxLength;
};

解题思路

  1. 建立一个Map对象theChars,存储无重复的单个字符;
  2. 以startIndex标定字符串子串起点;
  3. 以endIndex作为游标遍历,若出现与theChars内相同的字符,则记录当前theChars的size,与maxLength比较;
  4. 以startIndex += 1为子串起点(待优化),重复上述过程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值