首页 > 其他 > 详细

Longest Substring with At Most Two Distinct

时间:2015-01-25 06:29:37      阅读:238      评论:0      收藏:0      [点我收藏+]

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 }

 

Longest Substring with At Most Two Distinct

原文:http://www.cnblogs.com/reynold-lei/p/4247706.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!