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;
    }
  • 相关阅读:
    获得H.264视频分辨率的方法
    学习Mathematica
    关于LaTeX公式排版
    关于Jordan标准形
    关于surface gradient
    Jacobi-Anger expansion
    两个1/x类的广义函数
    积分计算相关内容
    关于multi-index
    关于$mathcal{D}(0,1)$上的一个有趣结论
  • 原文地址:https://www.cnblogs.com/littletail/p/5216497.html
Copyright © 2011-2022 走看看