3. Longest Substring Without Rep

2017-12-23  本文已影响0人  飞飞廉

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.

思路:

采用两个变量left和res记录最长子串的左边界和最长子串的长度。遍历字符串,如果没有在hash表中出现过,就更新长度res,如果出现过就更新左边界的值。最后给每一位字符串对应的位置填入hash表中(从1开始)。注意更新res长度的判断条件还有一个就是obj[s[i]]<left的值的时候即出现的这个字母即使存在过但他小雨左边界,也需要更新长度。

var lengthOfLongestSubstring = function(s) {
            var obj = {};
            var left = 0;
            var res = 0;
            for (var i = 0; i < s.length; i++) {
                if (!obj[s[i]] || obj[s[i]] < left) {
                    res = Math.max(res, i - left + 1);
                } else {
                    left=obj[s[i]];
                }
                 obj[s[i]] = i + 1;
            }
     return res
        };
上一篇下一篇

猜你喜欢

热点阅读