为有牺牲多壮志,敢教日月换新天。

[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 
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

热烈欢迎,请直接点击!!!

进入博主App Store主页,下载使用各个作品!!!

注:博主将坚持每月上线一个新app!!!

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 }

 

posted @ 2018-12-12 17:11  为敢技术  阅读(321)  评论(0编辑  收藏  举报