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):

 public class Solution {
public int lengthOfLongestSubstringTwoDistinct(String s) {
int result = 0;
int first = -1, second = -1;
int win_start = 0;
for(int i = 0; i < s.length(); i ++){
if(first < 0 || s.charAt(first) == s.charAt(i)) first = i;
else if(second < 0 || s.charAt(second) == s.charAt(i)) second = i;
else{
int min = first < second ? first : second;
win_start = min + 1;
if(first == min) first = i;
else second = i;
}
result = Math.max(result, i - win_start + 1);
}
return result;
}
}

最新文章

  1. android EditText inputType说明
  2. iOS - (集成支付宝SDK大坑总结)
  3. 怎么学习C++?
  4. 使用VAssistX给文件和函数添加注释-2015.12.31
  5. codevs 1922 骑士共存问题 网络流
  6. 解决MyEclipse吃内存以及卡死的方法 (转)
  7. Hibernate table schema 的设置与应用
  8. html5 geolocation配合百度地图api实现定位
  9. 剑指Offer——中国银行面试知识储备
  10. No X11 DISPLAY variable was set
  11. MVC object htmlAttributes,IDictionary&lt;string, object&gt; htmlAttributes 写法
  12. better-scroll项目中遇到的问题
  13. 2018牛客网暑假ACM多校训练赛(第三场)D Encrypted String Matching 多项式 FFT
  14. 2018年高教社杯全国大学生数学建模竞赛A题解题思路
  15. Nop 4.1版本已经迁移到.net core2.1版本
  16. 『转』VC++ webbrowser函数使用范例
  17. BZOJ1398: Vijos1382寻找主人 Necklace 字符串最小表示法
  18. Java多线程-Java多线程概述
  19. crc16算法,包括单片机和c#版本
  20. Git和Repo管理使用简要介绍

热门文章

  1. P4427 [BJOI2018]求和
  2. C# string 的一点属性、方法什么的
  3. XAF-DevExpress.ExpressApp.DC.Xpo.XpoTypeInfoSource 生成实体的过程-学习笔记
  4. zabbix3.4 监控路由器报错No Such Instance currently exists at this OID
  5. Idea for Mac 快捷键(快捷键选择:Mac OS X 10.5+)
  6. shell小记
  7. vue mock(模拟后台数据) 最简单实例(一)——适合小白
  8. pytorch中的Linear Layer(线性层)
  9. MySQL基础练习(二)
  10. python循环综合运用