Blog Archive

Showing posts with label Leetcode Challenge. Show all posts
Showing posts with label Leetcode Challenge. Show all posts

Count Number of Homogenous Substrings

Count Number of Homogenous Substrings

 Count Number of Homogenous Substrings- Data Structures and Algorithms-Leetcode Weekly Challenge


Given a string s, return the number of homogenous substrings of s. Since the answer may be too large, return it modulo 109 + 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:

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.
SOLUTION

int countHomogenous(string s)
{
    long long int num = 1e9 + 7;
    long long int result = 0;
    long long int count = 1;
    for (int i = 1; i < s.size(); i++)
    {
        if (s[i] == s[i - 1])
        {
            count++;
        }
        else
        {
            result += (count * (count + 1)) / 2;
            count = 1;
        }
    }
    result += (count * (count + 1)) / 2;
    result = result % num;
    return result;
}

Data Structures and Algorithms-Leetcode Weekly Challenge


Thank You...

Recent Post

Sort an array of 0s, 1s and 2s

  Sort an array of 0s, 1s and 2s- Data Structures   Sort an array of 0s, 1s and 2s- Data Structures Given an array of size N containing onl...