【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)。
相關文章
- 7.14 APPROX_COUNT_DISTINCTAPP
- 7.15 APPROX_COUNT_DISTINCT_AGGAPP
- 7.16 APPROX_COUNT_DISTINCT_DETAILAPPAI
- Leetcode 17 Letter Combinations of a Phone NumberLeetCode
- [LeetCode] 115. Distinct SubsequencesLeetCode
- 大資料下的Distinct Count(二):Bitmap篇大資料
- Leetcode – 017. Letter Combinations of a Phone NumberLeetCode
- Leetcode 38 Count and SayLeetCode
- 【Leetcode】1081. Smallest Subsequence of Distinct CharactersLeetCode
- LeetCode Letter Combinations of a Phone Number(017)解法總結LeetCode
- [leetcode]plus-oneLeetCode
- [LeetCode] 811. Subdomain Visit CountLeetCodeAI
- 【Leetcode】1395. Count Number of TeamsLeetCode
- region format is illegal, only digit, letter and - is allowed!(.env檔案中行內註釋導致!!)ORMGit
- LeetCode Patching Array All In OneLeetCode
- [LeetCode] 2257. Count Unguarded Cells in the GridLeetCode
- "ScrollView can host only one direct child"問題解決View
- [Laravel系列] 解決laravel中paginate()與distinct() count語句錯誤問題Laravel
- LeetCode - Easy - 66. Plus OneLeetCode
- 演算法練習--LeetCode--17. Letter Combinations of a Phone Number: 100%演算法LeetCode
- SparkStreaming報錯: Only one SparkContext may be running in this JVM (see SPARK-2243)SparkContextJVM
- [LeetCode] 2960. Count Tested Devices After Test OperationsLeetCodedev
- [LeetCode] 3184. Count Pairs That Form a Complete Day ILeetCodeAIORM
- LeetCode Greatest Common Divisor of Strings All In OneLeetCode
- LeetCode 394. Decode String All In OneLeetCode
- LeetCode 735. Asteroid Collision All In OneLeetCodeAST
- Swift 中 Substrings 與 StringSwift
- LeetCode 974 Subarray Sums Divisible by K All In OneLeetCode
- 222. Count Complete Tree Nodes(Leetcode每日一題-2020.11.24)LeetCode每日一題
- MySQL的COUNT語句--count(*)、 count(常量)、 count(列名)MySql
- Saprk distinct
- [LeetCode] 2962. Count Subarrays Where Max Element Appears at Least K TimesLeetCodeAPPAST
- LeetCode C++ 204. Count Primes【Math/Hash Table】簡單LeetCodeC++
- 使用monaco編輯器 報錯Can only have one anonymous define call per script file
- LeetCode1002. 查詢常用字元(雜湊表、count)LeetCode字元
- count(*)、count(1)和count(列名)的區別
- count (*) 和 count (1) 和 count (列名) 區別
- count(*) 和 count(1)和count(列名)區別