zoukankan      html  css  js  c++  java
  • [Swift]LeetCode1180. 统计只含单一字母的子串 | Count Substrings with Only One Distinct Letter

    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
    ➤微信公众号:山青咏芝(shanqingyongzhi)
    ➤博客园地址:山青咏芝(www.zengqiang.org
    ➤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 }
  • 相关阅读:
    使用路由传参时,query与params的区别!
    写前端页面步骤----vue+iview
    使用vue做表单验证
    vue中find函数
    @Controller和@RestController的区别?
    JavaScript 拥有动态类型
    Console的9种用法
    Navicat连接Oracle报ORA-12737错误
    oracle查询数据库连接数相关
    oracle存储过程把查询到的值更新到别的表
  • 原文地址:https://www.cnblogs.com/strengthen/p/11484244.html
Copyright © 2011-2022 走看看