LeetCode知识点总结 - 696

LeetCode 696. Count Binary Substrings

考点 难度
String Easy
题目

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;
}
上一篇:Mysql 5.6修改root密码的方式


下一篇:**黑哥带你从网络空间测绘看“SolarWinds Orion供应链攻击事件”**