[LeetCode] 1759. Count Number of Homogenous Substrings
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.
统计同构子字符串的数目。
给你一个字符串 s ,返回 s 中 同构子字符串 的数目。由于答案可能很大,只需返回对 109 + 7 取余 后的结果。
同构字符串 的定义为:如果一个字符串中的所有字符都相同,那么该字符串就是同构字符串。
子字符串 是字符串中的一个连续字符序列。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/count-number-of-homogenous-substrings
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
这是一道数学题。思路是扫描 input 字符串,当遇到连续出现的字符串的时候,统计连续出现的次数 count,同构子字符串的数目 = (1 + count) * count / 2,就是小学数学里的等差数列求和。注意 17 行需要再算一次,因为在for循环里,只有当前字母不同于上一个字母的时候才结算,这里我们需要最后再结算一次。
时间O(n)
空间O(1)
Java实现
1 class Solution { 2 public int countHomogenous(String s) { 3 final int MOD = (int) Math.pow(10, 9) + 7; 4 long res = 0; 5 char pre = s.charAt(0); 6 int count = 0; 7 for (int i = 0; i < s.length(); i++) { 8 char cur = s.charAt(i); 9 if (cur == pre) { 10 count++; 11 } else { 12 res += (long) (count + 1) * count / 2; 13 count = 1; 14 pre = cur; 15 } 16 } 17 res += (long) (count + 1) * count / 2; 18 return (int) (res % MOD); 19 } 20 }
相关题目
1180. Count Substrings with Only One Distinct Letter - 统计连续出现的相同字母
1513. Number of Substrings With Only 1s - 统计连续出现的1