
Sponsored
Sponsored
In this approach, we make use of two pointers to keep track of the start and end of a sequence of identical characters. As we iterate through the string, we update the end pointer when we find the same character, and on encountering a different character, we calculate the number of homogenous substrings formed using the formula for the sum of first n natural numbers: n * (n + 1) / 2, where n is the length of the sequence of identical characters. We repeat this process for each identified sequence and accumulate the total number of homogenous substrings.
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(1), as we only use a constant amount of extra space.
1#include <iostream>
2#include <string>
3#define MOD 1000000007
4
5using namespace std;
6
7int countHomogenous(string s) {
8 long count = 0;
9 int length = 1;
10 for (size_t i = 1; i < s.length(); ++i) {
11 if (s[i] == s[i - 1]) {
12 length++;
13 } else {
14 count = (count + (long)length * (length + 1) / 2) % MOD;
15 length = 1;
16 }
17 }
18 count = (count + (long)length * (length + 1) / 2) % MOD;
19 return (int)count;
20}
21
22int main() {
23 cout << countHomogenous("abbcccaa") << endl;
24 return 0;
25}The C++ solution follows the same logic as the C solution. We iterate through the string to maintain current consecutive character count and compute the homogenous substrings as sequences break, updating our count while taking care of the modulo constraint.
This approach involves counting the sequences of homogenous substrings by leveraging arithmetic progression's sum. By identifying the start and end of each homogenous substring part, we can determine the total count for those characters. We iterate through the string, find the size of each segment, and calculate total substrings using the arithmetic formula.
Time Complexity: O(n) where n is the length of the string.
Space Complexity: O(1) since no extra space is used apart from fixed variables.
In Java, string traversal combined with a counter variable, giving arithmetic sequence calculations facilitate the return of overall homogenous substring count.