• Longest Substring with At Most Two Distinct


    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 }
  • 相关阅读:
    2011年10月小记
    修改模拟器hosts文件
    2011年9月小记
    解决IIS7.5站点不能登录SQLEXPRESS
    EF 4.3 CodeBased Migrations
    2012年5月 小记
    Android对SD卡进行读写
    Tomcat for Eclipse
    ARR2.5 配置反向代理
    作业2浅谈数组求和java实验
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/4247706.html
Copyright © 2020-2023  润新知