159. Longest Substring with At Most Two Distinct Characters
Given a string, find the length of the longest substring T that contains at most 2 distinct characters.
For example, Given s = “eceba”
,
T is "ece" which its length is 3.
本题和sliding window比较类似,但是有一个差别就是,这里面的字符串是有重复的,而不是像之前几道题,是固定的长度,开始想的时候没有想出做法,看了答案才看明白,使用一个hashmap来做,用于存储最后一次出现过的index的值,然后每次size值大于指定值的时候,把最小的那个索引去掉,让low=index+1.代码如下:
1 public class Solution { 2 public int lengthOfLongestSubstringTwoDistinct(String s) { 3 if(s.length()<1) return 0; 4 Map<Character,Integer> map = new HashMap<>(); 5 int len = 0; 6 int hi = 0; 7 int lo = 0; 8 while(hi<s.length()){ 9 if(map.size()<=2){ 10 char c = s.charAt(hi); 11 map.put(c,hi); 12 hi++; 13 } 14 if(map.size()>=3){ 15 int i = s.length(); 16 for(int v:map.values()){ 17 i = Math.min(i,v); 18 } 19 char c = s.charAt(i); 20 map.remove(c); 21 lo = i+1; 22 } 23 len = Math.max(len,hi-lo); 24 } 25 return len; 26 } 27 }
本题我在做的时候有一个地方做错了,就是while循环里面的if size自己写的时候写在了一个if里面,为什么这么写不对,是因为当size的值刚好等于2,下一个元素是不一样的char的时候,while循环里面的长度就需要进行计算,而这一次没有进行计算。