【Leetcode】696. 计算二进制子字符串(Count Binary Substrings)

Leetcode - 696 Count Binary Substrings (Easy)

题目描述:给定一个由 0 和 1 组成的字符串,求有多少连续分组的子串。

Input: "00110011"
Output: 6
Explanation: There are 6 substrings that have equal number of consecutive 1's and 0's: "0011", "01", "1100", "10", "0011", and "01".
Input: "10101"
Output: 4
Explanation: There are 4 substrings: "10", "01", "10", "01" that have equal number of consecutive 1's and 0's.

解题思路:统计每个分组的个数,例如 0011 的分组个数为 2 2,能够组成的连续分组子串为 01 与 0011,遍历数组利用当前分组数量与前一个分组数量计算结果。

public int countBinarySubstrings(String s) {
    int prevLength = 0, curLength = 1, ans = 0;
    for (int i = 1; i < s.length(); i++) {
        if (s.charAt(i) == s.charAt(i - 1)) {
            curLength += 1;
        } else {
            prevLength = curLength;
            curLength = 1;
        }
        if (prevLength >= curLength) {
            ans += 1;
        }
    }
    return ans;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值