您的位置:首页 > 其它

【leetcode】3. Longest Substring Without Repeating Characters

2016-06-22 11:01 453 查看
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.

没有考虑到取最大值的问题

没有考虑到最后long的值也要和longest比较的问题

开头的算法是错的,要有一个定位,就是重复项从哪里开始算不重复的长度,用字典来存储以前的数据, 重复的情景是什么样子的情景,发生了什么比较重要,怎么判断重复,怎么判断长度,第一个重复的怎么算。

Your runtime beats 33.53% of javascriptsubmissions.

/**
* @param {string} s
* @return {number}
*/
var lengthOfLongestSubstring = function(s) {
var save = {};
var l_pos = 0;
var longest = 0;
var ll = s.length;
for(var i=0;i<ll;i++){
var char = s[i];
if(char in save){
if(save[char]>=l_pos){
var long = i - l_pos;
if(long>longest){
longest = long;
}
l_pos = save[char]+1;
save[char]=i;
}else{
save[char] = i;
}
}
save[char]=i;
}

return longest>i-l_pos?longest:i-l_pos;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode