当前位置 : 主页 > 手机开发 > 其它 >

[Swift]LeetCode1180. 统计只含单一字母的子串 | Count Substrings with Only One Distinct Le

来源:互联网 收集:自由互联 发布时间:2021-06-11
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ ?微信公众号:为敢(WeiGanTechnologies) ?博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
?微信公众号:为敢(WeiGanTechnologies)
?博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
?GitHub地址:https://github.com/strengthen/LeetCode
?原文地址:https://www.cnblogs.com/strengthen/p/11484244.html
?如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
?原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

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.

 

给你一个字符串 S,返回只含 单一字母 的子串个数。

示例 1:

输入: "aaaba"
输出: 8
解释: 
只含单一字母的子串分别是 "aaa", "aa", "a", "b"。
"aaa" 出现 1 次。
"aa" 出现 2 次。
"a" 出现 4 次。
"b" 出现 1 次。
所以答案是 1 + 2 + 4 + 1 = 8。

示例 2:

输入: "aaaaaaaaaa"
输出: 55

 

提示:

  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 }
网友评论