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;
}
Thank You...
No comments:
Post a Comment