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.
思路
持续更新prevRunLength
和curRunLength
,只要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;
}