在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given a string
Example 1: Input: S = "aaaba" Output: 8 Explanation: The substrings with one distinct letter are "aaa", "aa", "a", "b". "aaa" occurs 1 time. "aa" occurs 2 times. "a" occurs 4 times. "b" occurs 1 time. So the answer is 1 + 2 + 4 + 1 = 8. Example 2: Input: S = "aaaaaaaaaa" Output: 55
Constraints:
给你一个字符串 示例 1: 输入: "aaaba" 输出: 8 解释: 只含单一字母的子串分别是 "aaa", "aa", "a", "b"。 "aaa" 出现 1 次。 "aa" 出现 2 次。 "a" 出现 4 次。 "b" 出现 1 次。 所以答案是 1 + 2 + 4 + 1 = 8。 示例 2: 输入: "aaaaaaaaaa" 输出: 55
提示:
Runtime: 4 ms
Memory Usage: 21 MB
1 class Solution { 2 func countLetters(_ S: String) -> Int { 3 var arr:[Character] = Array(S) 4 arr.append("#") 5 var k:Int = 0 6 var c:Character = "#" 7 var ans:Int = 0 8 for i in 0..<arr.count 9 { 10 if arr[i] == c 11 { 12 k += 1 13 } 14 else 15 { 16 if c != "#" 17 { 18 ans += k * (k + 1) / 2 19 } 20 c = arr[i] 21 k = 1 22 } 23 } 24 return ans 25 } 26 }
|
请发表评论