★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤ micro-channel public number: to dare (WeiGanTechnologies)
➤ blog Park address: San-ching Wing Chi ( https://www.cnblogs.com/strengthen/ )
➤GitHub address: https://github.com/strengthen/LeetCode
➤ original address: HTTPS: //www.cnblogs. com / strengthen / p / 11484244.html
➤ If the address is not a link blog Park Yong Shan Chi, it may be crawling author of the article.
➤ text has been modified update! Click strongly recommended that the original address read! Support authors! Support the original!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
Given a string S
, return the number of substrings that have only one distinct letter.
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 <= S.length <= 1000
S[i]
consists of only lowercase English letters.
Give you a string S
, it returns the number of sub-strings contain only a single letter.
Example 1:
Input: "aaaba" Output: 8 Explanation: containing only a single sub-string are letters "aaa", "aa", "a", "b". "aaa" appear more than once. "aa" appears twice. "a" appears 4 times. "b" appear more than once. So the answer is 1 + 2 + 4 + 1 = 8.
Example 2:
Enter: "aaaaaaaaaa" Output: 55
prompt:
1 <= S.length <= 1000
S[i]
English only lowercase letters.
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 }