leetcode #3 Longest Substring Wi

2017-07-04  本文已影响0人  huntriver

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.

思路非常简单 从第一个字符开始向后遍历 当该字符在子串中已经出现过,将子串中第一次出现该字符之前的部分全部删掉。
重复以上步骤 找到最长的子串。

/**
 * @param {string} s
 * @return {number}
 */

var lengthOfLongestSubstring = function (s) {
    let temp = "";
    let maxLen = 0; //记录最长的子串长度
    for (let chart of s) {
        let index = temp.indexOf(chart);
        if (index >= 0) { //如果该字符已经出现过 删掉之前的部分。
            temp = temp.substring(index + 1);
        }
        temp += chart;
        if (temp.length > maxLen) {
            maxLen = temp.length;
        }
    }
    return maxLen;
};

上一篇 下一篇

猜你喜欢

热点阅读