- Leetcode PHP题解--D88 696. Count B
- 696. Count Binary Substrings
- 696. Count Binary Substrings
- 696. Count Binary Substrings
- 算法题,Count Binary Substrings
- LeetCode之Count Binary Substrings
- Leetcode 696. Count Binary Subst
- LeetCode笔记:696. Count Binary Sub
- LeetCode #1016 Binary String Wit
- LintCode 365. Count 1 in Binary
https://leetcode.com/contest/leetcode-weekly-contest-54/problems/count-binary-substrings/
Give a string s, count the number of non-empty (contiguous) 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.
Example 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".
Notice that some of these substrings repeat and are counted the number of times they occur.
Also, "00110011" is not a valid substring because all the 0's (and 1's) are not grouped together.
做这种题目好比做阅读理解...读懂题目就写出来了..溜了溜了
public int countBinarySubstrings(String s) {
if (s == null) return 0;
int res = 0;
for (int i = 0; i < s.length() - 1; i++) {
if (isAvailable(s, i)) {
res++;
}
}
return res;
}
private boolean isAvailable(String s, int index) {
int origin = s.charAt(index);
int len = 0;
int i;
for (i = index + 1; i < s.length(); i++) {
if (s.charAt(i) != origin) {
len = i - index;
break;
}
}
if (len == 0) return false;
for (int j = i; j < s.length(); j++) {
if (s.charAt(j) == origin) {
break;
}
len--;
if (len == 0) break;
}
return len == 0;
}
网友评论