LC.1180. Count Substrings with Only One Distinct Letter

痴心易碎 提交于 2019-11-29 12:09:13

在这里插入图片描述

class Solution:
    def countLetters(self, S: str) -> int:
        """
        统计连续相同字符出现的次数即可
        对于长度为n 的相同字符的字符串,他有 1+2+..n个子串
        """
        def sum_n(n):
            return (n+1)*n //2
        last_char, result, count, S = "$", 0, 0, S +"$"
        for char in S:
            if char == last_char:
                count += 1
            else:
                result += sum_n(count)
                count = 1
                last_char = char
        return result
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!