糖逗 发表于 2020-4-17 13:54:51

C++刷leetcode(1180. 统计只含单一字母的子串)【stack和queue都没有clear函数,deq...

本帖最后由 糖逗 于 2020-4-24 20:18 编辑

题目描述:
给你一个字符串 S,返回只含 单一字母 的子串个数。

示例 1:

输入: "aaaba"
输出: 8
解释:
只含单一字母的子串分别是 "aaa", "aa", "a", "b"。
"aaa" 出现 1 次。
"aa" 出现 2 次。
"a" 出现 4 次。
"b" 出现 1 次。
所以答案是 1 + 2 + 4 + 1 = 8。
示例 2:

输入: "aaaaaaaaaa"
输出: 55
 

提示:

1 <= S.length <= 1000
S 仅由小写英文字母组成。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/count-substrings-with-only-one-distinct-letter
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


#include <iostream>
#include<string>
#include<queue>
using namespace std;

int countLetters(string S) {
    deque<int> temp;
    int res = 0;
    for(auto cha :S){
      if(temp.empty()){
            temp.push_back(cha);
            continue;
      }
      if(cha != temp.back()){
            int len = temp.size();
            res += (len +1)*len/2;
            temp.clear();
      }
      temp.push_back(cha);
    }
    res += temp.size()*(temp.size() + 1)/2;
    return res;

}
int main(void){
        string input;
        cin >> input;
        cout << countLetters(input) << endl;
        return 0;
}



参考链接:https://leetcode-cn.com/problems/count-substrings-with-only-one-distinct-letter/solution/tong-ji-zhi-han-dan-yi-zi-mu-de-zi-chuan-by-leetco/
注意事项:
1.在c++中stack和queue都没有clear函数,deque有。

页: [1]
查看完整版本: C++刷leetcode(1180. 统计只含单一字母的子串)【stack和queue都没有clear函数,deq...