|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 糖逗 于 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[i] 仅由小写英文字母组成。
- 来源:力扣(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 ... zi-chuan-by-leetco/
注意事项:
1.在c++中stack和queue都没有clear函数,deque有。
|
|