第3题:Longest Substring Without Repeating Characters

来源:互联网 发布:linux清除文件夹内容 编辑:程序博客网 时间:2024/05/22 03:40

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 asubsequence and not a substring.


题目要求:求给定字符串最长子串的长度,该子串不包含重复字符。


编程语言:javascript

解法:算法复杂度为O(n)  思路:创建一个接收数组,遍历字符串。若当前字符不在接收数组中,则将其加入接收数组,更新最大长度,否则删除接收数组第一个元素。

/** * @param {string} s * @return {number} */var lengthOfLongestSubstring = function(s) {    if(s === "")    {        return 0;    }    if(s.length === 1)    {        return 1;    }    var j=0;    var resultArray = [];    var maxLength = 0;    while(j<s.length)    {        if(resultArray.indexOf(s.charAt(j)) < 0)        {            resultArray.push(s.charAt(j++));            maxLength = Math.max(maxLength,resultArray.length);        }else{            resultArray.shift();        }    }    return maxLength;};

还有一个失败的解法,编译器中能过但在leetcode中超时。。。原因是js中对数组的操作太过耗时。

/** * @param {string} s * @return {number} */var lengthOfLongestSubstring = function(s) {    if(s === "")    {        return 0;    }    if(s.length === 1)    {        return 1;    }    //临时计数    var count = 0;    //最大长度    var maxCount = 0;    //最长不重复字符串结果数组    var resultArray = new Array(s.length);    //临时不重复字符串数组    var tempArray = new Array(s.length);        for(var current_index = 0; current_index < s.length-1; ++current_index)    {      //清空临时数组                tempArray.splice(0,tempArray.length);                count = 0;        tempArray.push(s[current_index]);        ++count;                for(var next_index = current_index+1; next_index < s.length; ++next_index)        {                    //若当前元素不在临时数组中            if(tempArray.indexOf(s[next_index]) < 0)            {                ++count;                                tempArray.push(s[next_index]);            }else{                 break;            }        }        if(count > maxCount)                {                    maxCount = count;                }    }        return maxCount;   };




0 0
原创粉丝点击