zoukankan      html  css  js  c++  java
  • [Swift]LeetCode159.具有最多两个不同字符的最长子串 $ Longest Substring with At Most Two Distinct Characters

    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
    ➤微信公众号:山青咏芝(shanqingyongzhi)
    ➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
    ➤GitHub地址:https://github.com/strengthen/LeetCode
    ➤原文地址:https://www.cnblogs.com/strengthen/p/10063406.html 
    ➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
    ➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

    Given a string S, find the length of the longest substring T that contains at most two distinct characters.
    For example:
    Given S = “eceba”,
    T is “ece” which its length is 3.


    给定字符串S,找到最长子字符串T的长度,最多包含两个不同的字符。

    例如:

    给定S = “eceba”,

    T是“ece” ,长度为3。


     1 class Solution {
     2     func lengthOfLongestSubstringTwoDistinct(_ s:String) -> Int {
     3         var left:Int = 0
     4         var right:Int = -1
     5         var res:Int = 0
     6         for i in 1..<s.count
     7         {
     8             if s[i] == s[i - 1] {continue}
     9             if right >= 0 && s[right] != s[i]
    10             {
    11                 res = max(res, i - left)
    12                 left = right + 1
    13             }
    14             right = i - 1
    15         }
    16         return max(s.count - left, res) 
    17     }
    18 }
    19 
    20 extension String {        
    21     //subscript函数可以检索数组中的值
    22     //直接按照索引方式截取指定索引的字符
    23     subscript (_ i: Int) -> Character {
    24         //读取字符
    25         get {return self[index(startIndex, offsetBy: i)]}
    26     }
    27 }
  • 相关阅读:
    docker学习记录
    TCP/IP基础介绍
    JS对select操作
    js中删除table里所有行
    端口
    js中定时器的使用
    ASP.NET程序中常用的三十三种代码
    NHibernate学习(转)
    条面向对象设计的经验原则(转)
    客户端等select和input控件
  • 原文地址:https://www.cnblogs.com/strengthen/p/10063406.html
Copyright © 2011-2022 走看看