159. Longest Substring with At Most Two Distinct Characters

复制代码
package LeetCode_159

/**
 * 159. Longest Substring with At Most Two Distinct Characters
 * (Locked by leetcode)
 * https://www.lintcode.com/problem/longest-substring-with-at-most-two-distinct-characters/description
 *
 * Given a string s , find the length of the longest substring t that contains at most 2 distinct characters.

Example 1:
Input: "eceba"
Output: 3
Explanation: t is "ece" which its length is 3.

Example 2:
Input: "ccaabbb"
Output: 5
Explanation: t is "aabbb" which its length is 5.
 * */
class Solution {
    /*
   Sliding Window solution. Time complexity:O(n), Space complexity:O(256);
    * when moving i:
    * occMap[s[i]]--
    * if (occMap[s[i]]==0){
    *   counter--
    * }
    *
    * when moving j:
    * if (occMap[s[j]])==0{
    *   counter++
    * }
    * occMap[s[j]]++
    *
    * bestLength = max(bestLength, length of current window)=>max(bestLength, j-i+1)
    *
    * counter: how many distinct character we have
    *
    * valid window condition: window contains <= 2 distinct characters = window desirable
    * when move i: when the window becomes not desirable (counter>2)
    * when move j: as long as counter<=2 (as long as window desirable)
    *
    * Sliding Window Tech important point:
    * 1.when to move i, and what have to do when moving i;
    * 2.when to move j, and what have to do when moving j;
    * 3.when to update the goal;
    * */
    fun lengthOfLongestSubstringTwoDistinct(s: String): Int {
        val occMap = IntArray(256)
        var i = 0
        var j = 0
        var counter = 0
        var bestLength = 0
        while (j < s.length) {
            if (occMap[s[j].toInt()] == 0) {
                counter++
            }
            occMap[s[j].toInt()]++
            while (counter > 2) {
                occMap[s[i].toInt()]--
                if (occMap[s[i].toInt()] == 0) {
                    counter--
                }
                i++
            }
            bestLength = Math.max(bestLength, j - i + 1)
            j++
        }
        //print(bestLength)
        return bestLength
    }
}
复制代码

 

posted @   johnny_zhao  阅读(134)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示