[Swift]LeetCode159.具備最多兩個不一樣字符的最長子串 $ Longest Substring with At Most Two Distinct Characters

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-zxmpqpjq-me.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★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.git


給定字符串S,找到最長子字符串T的長度,最多包含兩個不一樣的字符。github

例如:數組

給定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 }
相關文章
相關標籤/搜索