力扣696 计数二进制子串

在这里插入图片描述

第一次代码

#include <iostream>
using namespace std;
#include <string>
#include <unordered_map>
#include <algorithm>

int main()
{
    string s = "110001101011";

    cout << "字符串 s 为: ";
    for (int i = 0; i < s.size(); i++) {
        cout << s[i] << " ";
    }
    cout << endl;

    int n = s.size(), count1 = 1;
    vector <int> num;
    for (int i = 0; i < n - 1; i++) {  //这个for循环只是为了计算出连续的相同的数字的个数
        if (s[i] == s[i + 1]) {
            count1++;
            if (i == n - 2) {  //最后一个索引处理
                num.push_back(count1);
                break;
            }
        }
        else
        {
            num.push_back(count1);
            count1 = 1;
        }
        if (i == n - 2) {  //最后一个索引处理
            num.push_back(count1);
            break;
        }
    }
    cout << "num数组中重复数字如下: ";
    for (int i = 0; i < num.size(); i++) {
        cout  << num[i]<<" ";
    }
    cout << endl;

    int m = num.size(), result, count2 = 0;
    for (int i = 0; i < m - 1; i++) {  //计算连续子串出现的次数
        num[i] >= num[i + 1] ? count2 += num[i + 1] : count2 += num[i];
    }
    result = count2;
    cout << "结果为:" << result;
    cout << endl;

	system("pause");
	return 0;
}

在这里插入图片描述

第二次代码

#include <iostream>
using namespace std;
#include <string>
#include <unordered_map>
#include <algorithm>

int main()
{
    string s = "110001101011";

    cout << "字符串 s 为: ";
    for (int i = 0; i < s.size(); i++) {
        cout << s[i] << " ";
    }
    cout << endl;

    vector<int> counts;
    int ptr = 0, n = s.size();
    while (ptr < n) {
        char c = s[ptr];  // while循环取出每一个字符
        int count = 0;
        while (ptr < n && s[ptr] == c) { //计数,计算和c相同的字符的个数
            ++ptr;
            ++count;
        }
        counts.push_back(count);
    }
    cout << "counts数组中重复数字如下: ";
    for (int i = 0; i < counts.size(); i++) {
        cout << counts[i] << " ";
    }
    cout << endl;

    int ans = 0;  //这边和我的想法是一样的,就是两两对比取更小的那个
    for (int i = 1; i < counts.size(); ++i) {
        ans += min(counts[i], counts[i - 1]);
    }
    cout << "最后结果: " << ans << endl;


	system("pause");
	return 0;
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值