public int lengthOfLongestSubstring(String s) {
int maxLen=-1;
int left=0,right=0;
int k=4;
Map<Character,int[]>map=new HashMap<>(); // 下标0表示索引,1表示计数
while(right<s.length()) {
int f=-1;
if(map.get(s.charAt(right))==null||
map.get(s.charAt(right))[1]<k||
map.get(s.charAt(right))[0]<left) {
maxLen=Math.max(maxLen, right-left+1);
}else {
left=map.get(s.charAt(right))[0]+1;
int index=map.get(s.charAt(right))[0];
int count=map.get(s.charAt(right))[1];
map.put(s.charAt(right), new int[] {index,count-1});
for(int i=left;i<right;i++) {
if(s.charAt(right)==s.charAt(i)) {
f=i;break;
}
}
}
if(map.get(s.charAt(right))!=null) {
map.put(s.charAt(right), new int[] {f!=-1?f:map.get(s.charAt(right))[0],
map.get(s.charAt(right))[1]+1
});
}else {
map.put(s.charAt(right), new int[] {right,1});
}
right++;
}
return maxLen;
}
力扣《至多包含 K 个不同字符的最长子串》
最新推荐文章于 2024-11-08 15:35:46 发布