
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.
1class Solution {
2 private static final int MOD = 1000000007;
3
4 public int countHomogenous(String s) {
5 long count = 0;
6 int length = 1;
7 for (int i = 1; i < s.length(); i++) {
8 if (s.charAt(i) == s.charAt(i - 1)) {
9 length++;
10 } else {
11 count = (count + (long) length * (length + 1) / 2) % MOD;
12 length = 1;
13 }
14 }
15 count = (count + (long) length * (length + 1) / 2) % MOD;
16 return (int) count;
17 }
18
19 public static void main(String[] args) {
20 Solution sol = new Solution();
21 System.out.println(sol.countHomogenous("abbcccaa"));
22 }
23}In Java, the logic remains consistent with C/C++. The character comparisons are done using charAt and the count is updated using integer arithmetic while taking care of overflow with modulo operation.
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.