在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given a string S, find the length of the longest substring T that contains at most two distinct characters. 给定字符串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 }
|
请发表评论