Problem
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.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Solution
Method 1 - Two pointer technique
To solve the problem of counting homogeneous substrings, we can use a two-pointer technique. The idea is to maintain a window of consecutive identical characters and count the homogeneous substrings within this window.
Approach
- Initialization:
- Initialize a variable
ans
to store the result and a pointerl
to mark the start of the current window of identical characters. - Define a constant
MOD
for the modulo operation.
- Initialize a variable
- Iterate Through the String:
- Use a pointer
r
to traverse through the string. - For each character, check if it is the same as the character at the start of the window (
s[l]
). - If it is, add the length of the current homogeneous substring window (
r - l + 1
) toans
. - If it is not, reset the start of the window to the current position (
l = r
) and count this new single character as a separate homogeneous substring. - Apply the modulo operation to
ans
at each step to ensure the result fits within the limit.
- Use a pointer
- Return the Result:
- Return
ans
as an integer.
- Return
Code
|
|
|
|
Complexity
- Time:
O(n)
, wheren
is the length of the string. We traverse the string once and perform constant-time operations within the loop. - Space:
O(1)
, as we use a fixed amount of additional space for variables.