Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

第三题 - 无重复最长子串 #4

Open
laizimo opened this issue May 23, 2020 · 0 comments
Open

第三题 - 无重复最长子串 #4

laizimo opened this issue May 23, 2020 · 0 comments

Comments

@laizimo
Copy link
Owner

laizimo commented May 23, 2020

题目描述

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

示例 1:
输入: "abcabcbb"
输出: 3 
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。

示例 2:
输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。

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

算法

双指针法

答案

/**
 * 双指针法
 */
var lengthOfLongestSubstring = function(s) {
    //#1 设置最大字符串 | 可变字符串
    let maxStr = '';
    let str = ''
    //#2 遍历字符串
    for (let i = 0; i < s.length; i++) {
        //#3 取字符,判断str是否存在
        let chat = s[i];
        let index = str.indexOf(chat);
        if (index === -1) {
            //#4 不存在,str相加与maxStr比较
            str += chat;
            if (str.length > maxStr.length) maxStr = str;
        } else {
            //#5 存在,加上当前字符,然后截取重复字符之后的字符串
            str += chat;
            str = str.slice(index + 1);
        }
    }
    return maxStr.length;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant