iwfe / leetcode

3 stars 0 forks source link

3. Longest Substring Without Repeating Characters #3

Open lancui1110 opened 7 years ago

lancui1110 commented 7 years ago

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.
lancui1110 commented 7 years ago
/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLongestSubstring = function(s) {
    if (s.length === 0) return 0
    var res = {}, len = 0
    for (var i=0, j=0; i < s.length; i++) {
        var w = s.charAt(i), resw = res[w]
        if (resw !== undefined) {
            j = Math.max(j, resw + 1)
        }
        res[w] = i
        len = Math.max(len, i - j + 1)
    }
    return len
};
evelynlab commented 7 years ago

/ 思路:创建一个数组用于存放不重复的字符串,遍历,没有重复则Push进数组;重复了,则记录重复的索 引,删除重复的索引之前的元素重新开始push, 同时一直保持记录数组的最大长度 / var lengthOfLongestSubstring = function(s) { var maxLength = 0, // substr = []; //存放不重复子串 for (var i = 0, l = s.length; i<l; i++){ var repeatIndex = substr.indexOf(s[i]); if (repeatIndex === -1){//没有重复 substr.push(s[i]); maxLength = Math.max(substr.length, maxLength) } else{//重复 substr = substr.slice(repeatIndex+1); substr.push(s[i]); maxLength = Math.max(substr.length, maxLength) } } return maxLength; };