zoukankan      html  css  js  c++  java
  • [Locked] Longest Substring with At Most Two Distinct Characters

    Longest Substring with At Most Two Distinct Characters

    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.

    分析:

      最多包含两个不同字母的子串,至少要遍历一遍,复杂度为O(n),而要实现O(n)复杂度,用移动窗口思想即可。

    代码:

    int lentwoc(string s) {
        if(s.empty())
            return 0;
        char a = s[0], b = '';
        //alast为a字母最后出现的位置,blast为b字母最后出现的位置,lastpos为新两元序列的开端位置,maxl为全局最长序列长度
        int alast = 0, blast = -1, lastpos = 0, maxl = 0;
        for(int i = 1; i < s.length(); i++) {
            //开启新两元序列
            if(s[i] != a && s[i] != b) {
                //记录前一个两元序列长度
                maxl = max(i - lastpos, maxl);
                if(alast < blast) {
                    alast = i;
                    a = s[i];
                    lastpos = blast;
                }
                else {
                    blast = i;
                    b = s[i];
                    lastpos = alast;
                }
            }
            else
                s[i] == a ? alast = i : blast = i;
        }
        return maxl;
    }
  • 相关阅读:
    (图论)树的直径
    HDU 4607
    类属性的增删改查
    python内置常用模块
    字典的使用
    元组的使用
    列表的基本函数
    字符串练习题
    python3.7字符串基本函数
    python简单的while语句和if语句的练习
  • 原文地址:https://www.cnblogs.com/littletail/p/5216497.html
Copyright © 2011-2022 走看看