标签:基础题 出现 repeat without eating substr mat param 基础
最长无重复字符的子串。
题意是给一个input字符串,请输出其最长的,没有重复字符的substring。这是two pointer/sliding window的基础题。例子
Example 1:
Input: "abcabcbb" Output: 3 Explanation: The answer is
"abc"
, with the length of 3.Example 2:
Input: "bbbbb" Output: 1 Explanation: The answer is
"b"
, with the length of 1.Example 3:
Input: "pwwkew" Output: 3 Explanation: 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.
思路是用一个hashmap或者hashset,记录当前遍历到的character是否出现过,再用两个指针维护substring的上下界。
时间O(n)
空间O(n) - hashset
1 /** 2 * @param {string} s 3 * @return {number} 4 */ 5 var lengthOfLongestSubstring = function(s) { 6 let map = {}; 7 let max = 0; 8 let i = 0; 9 let j = 0; 10 while (j < s.length) { 11 if (map[s[j]]) { 12 map[s[i]] = null; 13 i++; 14 } else { 15 map[s[j]] = true; 16 max = Math.max(max, j - i + 1); 17 j++; 18 } 19 } 20 return max; 21 };
[LeetCode] 3. Longest Substring Without Repeating Characters
标签:基础题 出现 repeat without eating substr mat param 基础
原文地址:https://www.cnblogs.com/aaronliu1991/p/12190151.html