【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;
}

你可能感兴趣的:(LeetCode,字符串)