Formatted question description: https://leetcode.ca/all/1759.html

1759. Count Number of Homogenous Substrings

Level

Medium

Description

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 <= s.length <= 10^5
  • s consists of lowercase letters.

Solution

First, find all longest substrings such that all characters in the substring are the same. Next, calculate the count of each longest substring. If a longest substring have length n, then the number of homogeneous substrings in such a substring is n * (n + 1) / 2. Finally, return the total count.

class Solution {
    public int countHomogenous(String s) {
        final int MODULO = 1000000007;
        long totalCount = 0;
        int length = s.length();
        char prev = '0';
        int consecutive = 0;
        for (int i = 0; i < length; i++) {
            char c = s.charAt(i);
            if (c == prev)
                consecutive++;
            else {
                long curCount = (long) consecutive * (consecutive + 1) / 2 % MODULO;
                totalCount = (totalCount + curCount) % MODULO;
                consecutive = 1;
                prev = c;
            }
        }
        long curCount = (long) consecutive * (consecutive + 1) / 2 % MODULO;
        totalCount = (totalCount + curCount) % MODULO;
        return (int) totalCount;
    }
}

All Problems

All Solutions