Count Substrings with Only One Distinct Letter
给一个String, 问里面多少个substring只有一个不同的字符.
首先一个string, 比如aaaaa, 那么里面的只有一个不同字符的是n*(n+1) / 2个子string. 然后找就行了.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class Solution { public: int countLetters(string S) { int res = 0; int cur = 1; for(int i = 1; i < S.length(); i++) { if(S[i] != S[i - 1]){ res += cur * (cur + 1) / 2; cur = 1; }else{ cur++; } } res += cur * (cur + 1) / 2; return res; } }; |