1759. Count Number of Homogenous Substrings

复制代码
package LeetCode_1759

/**
 * 1759. Count Number of Homogenous Substrings
 * https://leetcode.com/problems/count-number-of-homogenous-substrings/
 * Given a string s, return the number of homogenous substrings of s.
 * Since the answer may be too large, return it modulo 10^9 + 7.
A string is homogenous if all the characters of the string are the same.
A substring is a contiguous sequence of characters within a string.

Example 1:
Input: s = "abbcccaa"
Output: 13
Explanation: The homogenous substrings are listed as below:
"a"   appears 3 times.
"aa"  appears 1 time.
"b"   appears 2 times.
"bb"  appears 1 time.
"c"   appears 3 times.
"cc"  appears 2 times.
"ccc" appears 1 time.
3 + 1 + 2 + 1 + 3 + 2 + 1 = 13.

Example 2:
Input: s = "xy"
Output: 2
Explanation: The homogenous substrings are "x" and "y".

Example 3:
Input: s = "zzzzz"
Output: 15

Constraints:
1. 1 <= s.length <= 10^5
2. s consists of lowercase letters.
 * */
class Solution {
    /*
    Solution: keep counting the same char then update sameCharCount and result,
    and reset sameCharCount=1 when current char not equal last char;
    Time:O(n), Space:O(1)
    * */
    fun countHomogenous(s: String): Int {
        val mod = 1000000007
        var lastChar: Char? = null
        var result = 0
        var sameCharCount = 0
        for (c in s) {
            if (lastChar == null || lastChar == c) {
                sameCharCount++
            } else {
                sameCharCount = 1
            }
            lastChar = c
            result = (result + sameCharCount) % mod
        }
        return result
    }
}
复制代码

 

posted @   johnny_zhao  阅读(25)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2020-08-15 515. Find Largest Value in Each Tree Row
2020-08-15 286. Walls and Gates (Solution 1)
2020-08-15 408. Valid Word Abbreviation
点击右上角即可分享
微信分享提示