Longest Substring with At Most Two Distinct

最长两字符子串算法
本文介绍了一种寻找字符串中最长包含最多两个不同字符的子串算法。通过使用两个指针记录窗口中两种字符最后出现的位置,并随着遍历更新窗口起始位置的方法,实现了O(n)的时间复杂度和O(1)的空间复杂度。

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.

用p1 & p2 两个pointer分别纪录当前window里两个character最后一次发生时的index,用start纪录window开始时的index。
从index 0开始遍历String:

如果当前的character在window内,update相应的pointer。

如果不在,比较两个character的pointer,去掉出现较早的那个character, 更新start=min(p1,p2)+1

时间复杂度是O(n), 空间复杂度是O(1):

 

 1 public class Solution {
 2     public int lengthOfLongestSubstringTwoDistinct(String s) {
 3         int result = 0;
 4         int first = -1, second = -1;
 5         int win_start = 0;
 6         for(int i = 0; i < s.length(); i ++){
 7             if(first < 0 || s.charAt(first) == s.charAt(i)) first = i;
 8             else if(second < 0 || s.charAt(second) == s.charAt(i)) second = i;
 9             else{
10                 int min = first < second ?  first : second;
11                 win_start = min + 1;
12                 if(first == min) first = i;
13                 else second = i;
14             }
15             result = Math.max(result, i - win_start + 1);
16         }
17         return result;
18     }
19 }

 

转载于:https://www.cnblogs.com/reynold-lei/p/4247706.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值