加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

[Swift]LeetCode1180. 统计只含单一字母的子串 | Count Substri

发布时间:2020-12-14 04:26:06 所属栏目:百科 来源:网络整理
导读:★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ ?微信公众号:为敢(WeiGanTechnologies) ?博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/) ?GitHub地址:https://github.com/strengthen/LeetCode ?原文

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
?微信公众号:为敢(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 }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读