【JavaScript】Leetcode 3.无重复字符的最长子串
2020-07-18 05:07
225 查看
题目描述
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例
示例 1:
输入: "abcabcbb" 输出: 3 解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例 2:
输入: "bbbbb" 输出: 1 解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
示例 3:
输入: "pwwkew" 输出: 3 解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。 请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
暴力思路
双指针遍历。存个临时字符串tempString,使用双指针i,j,从头开始,i不动,j往后移动,临时字符串逐个增加字符,一旦碰到和位置i字符重复的字符(判断方法是用indexof()),临时字符串清空,i往后移动一位,j重新从i后面开始移动。耗时328ms
var lengthOfLongestSubstring = function(s) { if (s.length <=1){ return s.length; } let max = 0; let tempString = s[0]; let i=0,j=1; while(j<s.length){ if(tempString.indexOf(s[j])>=0){ max = max > (j-i)? max:(j-i); i++; j=i+1; tempString =s[i]; continue; } tempString += s[j]; j++; } if(tempString.length>max){max = tempString.length;} return max; };
滑动窗口解法
看了官方题解,滑动窗口解法。也是双指针,左指针和右指针构造了一个滑动的窗口。每一轮将左指针向右移动一格,不断地向右移动右指针,直到遇到重复的字符。在移动结束后,这个子串就对应着以左指针开始的,不包含重复字符的最长子串。
时间复杂度:O(N),其中 N 是字符串的长度。左指针和右指针分别会遍历整个字符串一次。空间复杂度最多有O(128),128是字符集的长度
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/solution/wu-zhong-fu-zi-fu-de-zui-chang-zi-chuan-by-leetc-2/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
var lengthOfLongestSubstring = function(s) { if (s.length==0||s.length==1) return s.length; let right=-1,ans=0; let occ = new Set(); for(let left=0;left<s.length-1;left++){ if(left!=0){ occ.delete(s[left-1]); } for(;right<s.length;right++){ if(occ.has(s[right])){ break; } occ.add(s[right]); } ans = Math.max(ans,right-left); } return ans; };
相关文章推荐
- 【Leetcode一刷】3.无重复字符的最长子串
- Leetcode(C++)——3. 无重复字符的最长子串
- LeetCode 3. 无重复字符的最长子串
- LeetCode 3. 无重复字符的最长子串
- Leetcode 3.无重复字符的最长子串
- 【LeetCode】3.无重复字符的最长子串 结题报告 (C++)
- LeetCode-3.无重复字符的最长子串
- Leetcode-3.无重复字符的最长子串(python)
- [Leetcode] 3.无重复字符的最长子串
- leetcode 3. 无重复字符的最长子串(Java 版)
- 【leetcode】3. 无重复字符的最长子串
- LeetCode 3. 无重复字符的最长子串
- LeetCode3. 无重复字符的最长子串(python)
- LeetCode 3. 无重复字符的最长子串
- LeetCode 3. 无重复字符的最长子串
- LeetCode-3.无重复字符的最长子串
- Leetcode:3.无重复字符的最长子串
- Leetcode3. 无重复字符的最长子串
- 5/2 LeetCode每日一题 3. 无重复字符的最长子串
- 【LeetCode】JavaScript -----无重复字符的最长子串