[Swift]LeetCode1180. 統計只含單一字母的子串 | Count Substrings with Only One Distinct Letter

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

Given a string S, return the number of substrings that have only one distinct letter.git

 

Example 1:github

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:app

  • 1 <= S.length <= 1000
  • S[i] consists of only lowercase English letters.

 

給你一個字符串 S,返回只含 單一字母 的子串個數。spa

示例 1:code

輸入: "aaaba"
輸出: 8
解釋: 
只含單一字母的子串分別是 "aaa", "aa", "a", "b"。
"aaa" 出現 1 次。
"aa" 出現 2 次。
"a" 出現 4 次。
"b" 出現 1 次。
因此答案是 1 + 2 + 4 + 1 = 8。

示例 2:htm

輸入: "aaaaaaaaaa"
輸出: 55

 

提示:blog

  1. 1 <= S.length <= 1000
  2. S[i] 僅由小寫英文字母組成。

 

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