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

[Swift]LeetCode1180. 统计只含单一字母的子串 | Count Substrings with Only One Distinct Letter,第1张

概述★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ ?微信公众号:为敢(WeiGanTechnologies) ?博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/) ?GitHub地址:https://github.com/strengthen/LeetCode ?原文地址:https://www.cnblogs.com/s

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
?微信公众号:为敢(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: 8Explanation: 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 <= S.length <= 1000 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(@H_301_98@"@H_301_98@#@H_301_98@") 5         var k:Int = 0 6         var c:Character = @H_301_98@"@H_301_98@#@H_301_98@" 7         var ans:Int = 0 8         for i in 0..<arr.count 9         {10             if arr[i] == c11             {12                 k += 113             }14             else15             {16                 if c != @H_301_98@"@H_301_98@#@H_301_98@"17                 {18                     ans += k * (k + 1) / 219                 }20                 c = arr[i]21                 k = 122             }23         }24         return ans25     }26 }
总结

以上是内存溢出为你收集整理的[Swift]LeetCode1180. 统计只含单一字母的子串 | Count Substrings with Only One Distinct Letter全部内容,希望文章能够帮你解决[Swift]LeetCode1180. 统计只含单一字母的子串 | Count Substrings with Only One Distinct Letter所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/999775.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存