LeetCode-1759. Count Number of Homogenous Substrings [Medium]-Analysis and Code (Java)

LeetCode-1759. Count Number of Homogenous Substrings [Count Number of Homogenous Substrings] [Medium]-Analysis and Code [Java]

1. Topic

Give you a string s and return the number of isomorphic substrings in s. Since the answer may be large, just return the result after taking the remainder of 10^9 + 7.
The definition of a isomorphic string is: if all characters in a string are the same, then the string is an isomorphic string.
A substring is a continuous sequence of characters in a string.

Example 1:

输入:s = "abbcccaa"
输出:13
解释:同构子字符串如下所列:
"a"   出现 3 次。
"aa"  出现 1 次。
"b"   出现 2 次。
"bb"  出现 1 次。
"c"   出现 3 次。
"cc"  出现 2 次。
"ccc" 出现 1 次。
3 + 1 + 2 + 1 + 3 + 2 + 1 = 13

Example 2:

输入:s = "xy"
输出:2
解释:同构子字符串是 "x" 和 "y" 。

Example 3:

输入:s = "zzzzz"
输出:15

prompt:

  • 1 <= s.length <= 105
  • s consists of lowercase strings

Source: LeetCode (LeetCode)
Link: https://leetcode-cn.com/problems/count-number-of-homogenous-substrings
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Two, analysis and code

1. Direct calculation

(1) Thinking

For a string of the same character with a length of l, the number of isomorphic substrings is 1 + 2 +… + l = l * (l + 1) / 2, just calculate it directly.
Because the calculation result may exceed the range of int, pay attention to type conversion.

(2) Code

class Solution {
    
    
    public int countHomogenous(String s) {
    
    
        char[] c = s.toCharArray();
        int n = c.length, m = 1000000007, i = 0, ans = 0;
        while (i < n) {
    
    
            int len = 1;
            while (i + len < n && c[i + len] == c[i])
                len++;
            ans += ((len * (len + 1L)) % m) >> 1; 
            i += len;
        }
        return ans;
    }
}

(3) Results

Execution time: 9 ms, beating 100.00% of users
in all Java submissions ; memory consumption: 39 MB, beating 100.00% of users in all Java submissions.

Three, other

Nothing.

Guess you like

Origin blog.csdn.net/zml66666/article/details/113873453