[LeetCode] 159. Longest Substring with At Most Two Distinct Characters
Posted aaronliu1991
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 159. Longest Substring with At Most Two Distinct Characters相关的知识,希望对你有一定的参考价值。
最多有两个不同字符的最长子串。题意是给一个字符串,请返回一个最长子串的长度。子串的要求是最多只有两个不同的字母。例子,
Example 1:
Input: "eceba" Output: 3 Explanation: tis "ece" which its length is 3.Example 2:
Input: "ccaabbb" Output: 5 Explanation: tis "aabbb" which its length is 5.
这题依然是用到sliding window的思想。给左右两个指针,并且创建一个hashmap,key是遍历到的字母,value是字母最后一次出现位置的index。扫描的时候,一开始只让右指针移动,把遍历到的字母和当前的坐标值加入hashmap。此时最大子串的长度就是左右指针的间距。当右指针遍历到第三个不同字母的时候,需要扫描hashmap,找到value(记为leftmost)最小的那个key并且删除这个键值对。此时左指针的位置是leftmost + 1。
时间O(n)
空间O(1) - 虽然有hashmap但是size很小,只有26个字母
1 /** 2 * @param {string} s 3 * @return {number} 4 */ 5 var lengthOfLongestSubstringTwoDistinct = function (s) { 6 let map = new Map(); 7 let left = 0; 8 let max = 0; 9 for (let right = 0; right < s.length; right++) { 10 map.set(s[right], right); 11 if (map.size > 2) { 12 let leftMostChar = null; 13 let leftMostIndex = Infinity; 14 for (let [char, index] of map) { 15 if (index < leftMostIndex) { 16 leftMostChar = char; 17 leftMostIndex = index; 18 } 19 } 20 map.delete(leftMostChar); 21 left = leftMostIndex + 1; 22 } 23 max = Math.max(max, right - left + 1); 24 } 25 return max; 26 };
以上是关于[LeetCode] 159. Longest Substring with At Most Two Distinct Characters的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode] 159. Longest Substring with At Most Two Distinct Characters
leetcode 159. Longest Substring with At Most Two Distinct Characters 求两个字母组成的最大子串长度 --------- jav
[LC] 159. Longest Substring with At Most Two Distinct Characters