g1701_1800.s1759_count_number_of_homogenous_substrings.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java21 Show documentation
Show all versions of leetcode-in-java21 Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g1701_1800.s1759_count_number_of_homogenous_substrings;
// #Medium #String #Math #2022_04_30_Time_19_ms_(42.40%)_Space_51.3_MB_(28.80%)
/**
* 1759 - Count Number of Homogenous Substrings\.
*
* Medium
*
* 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 1:**
*
* **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.
*
* **Example 2:**
*
* **Input:** s = "xy"
*
* **Output:** 2
*
* **Explanation:** The homogenous substrings are "x" and "y".
*
* **Example 3:**
*
* **Input:** s = "zzzzz"
*
* **Output:** 15
*
* **Constraints:**
*
* * 1 <= s.length <= 105
* * `s` consists of lowercase letters.
**/
public class Solution {
public int countHomogenous(String s) {
int total = 0;
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (i > 0 && s.charAt(i) == s.charAt(i - 1)) {
count++;
} else {
count = 1;
}
total = (total + count) % 1000000007;
}
return total;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy