【Leetcode】1180. Count Substrings with Only One Distinct Letter

题目地址:

https://leetcode.com/problems/count-substrings-with-only-one-distinct-letter/

给定一个字符串 s s s,问其有多少个只含同一个字符的子串。

对于一个长 l l l的且只含一种字符的字符串,其子串个数应该是 ∑ i = 1 l i = ( 1 + l ) l 2 \sum _{i=1}^{l}i=\frac{(1+l)l}{2} i=1li=2(1+l)l(这可以理解为枚举子串开头字符然后累加)。所以只需要每次截取出 s s s中只含同一个字符的子串然后累加即可。代码如下:

public class Solution {
     
    public int countLetters(String S) {
     
        int res = 0;
        
        for (int i = 0; i < S.length(); i++) {
     
            int j = i;
            while (j < S.length() && S.charAt(j) == S.charAt(i)) {
     
                j++;
            }
            res += (1 + j - i) * (j - i) / 2;
            
            i = j - 1;
        }
        
        return res;
    }
}

时间复杂度 O ( l s ) O(l_s) O(ls),空间 O ( 1 ) O(1) O(1)

你可能感兴趣的:(#,二分,位运算与数学,字符串,leetcode,算法)