力扣题:字符的统计-12.6

2023-12-13 10:15:56

力扣题-12.6

[力扣刷题攻略] Re:从零开始的力扣刷题生活

力扣题1:696. 计数二进制子串

解题思想:先统计连续的0和连续的1的个数,然后进行相加即可(想不到一点)

在这里插入图片描述

class Solution(object):
    def countBinarySubstrings(self, s):
        """
        :type s: str
        :rtype: int
        """
        count = []
        temp = s[0]
        num = 1
        for i in range(1,len(s)):
            if s[i]==temp:
                num +=1
            else:
                count.append(num)
                temp = s[i]
                num = 1
        count.append(num)
        result = 0
        for i in range(1,len(count)):
            result += min(count[i],count[i-1])
        return result
class Solution {
public:
    int countBinarySubstrings(string s) {
        std::vector<int> count;
        char temp = s[0];
        int num = 1;

        for (int i = 1; i < s.length(); ++i) {
            if (s[i] == temp) {
                num += 1;
            } else {
                count.push_back(num);
                temp = s[i];
                num = 1;
            }
        }
        count.push_back(num);
        int result = 0;
        for (int i = 1; i < count.size(); ++i) {
            result += std::min(count[i], count[i - 1]);
        }
        return result;        
    }
};

文章来源:https://blog.csdn.net/yumeng3866/article/details/134852581
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。