其他分享
首页 > 其他分享> > LeetCode知识点总结 - 696

LeetCode知识点总结 - 696

作者:互联网

LeetCode 696. Count Binary Substrings

考点难度
StringEasy
题目

Give a binary string s, return the number of non-empty substrings that have the same number of 0's and 1's, and all the 0's and all the 1's in these substrings are grouped consecutively.
Substrings that occur multiple times are counted the number of times they occur.

思路

持续更新prevRunLengthcurRunLength,只要prevRunLength >= curRunLength答案就加一。

答案
public int countBinarySubstrings(String s) {
        int prevRunLength = 0, curRunLength = 1, res = 0;
        for (int i=1;i<s.length();i++) {
            if (s.charAt(i) == s.charAt(i-1)) curRunLength++;
            else {
                prevRunLength = curRunLength;
                curRunLength = 1;
            }
            if (prevRunLength >= curRunLength) res++;
        }
        return res;
}

标签:知识点,696,curRunLength,int,res,number,prevRunLength,occur,LeetCode
来源: https://blog.csdn.net/m0_59773145/article/details/122083241