您的位置:首页 > 其它

Leetcode 696 Count Binary Substrings

2018-01-31 21:25 246 查看

Leetcode 696 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, an
4000
d 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.

Example 2:
Input: "10101"
Output: 4
Explanation: There are 4 substrings: "10", "01", "10", "01" that have equal number of consecutive 1's and 0's.

Note:
· s.length will be between 1 and 50,000.
· s will only consist of "0" or "1" characters.


一道easy题想的挺久的。。。

思路

按顺序统计字符串中连续出现‘1’和‘0’的个数,按顺序分别保存在一个数组中。最终结果就是这个数组两两相邻的数中最小的数的和。

对于‘00110011’,该数组为2,2,2,2

所以答案是 2 + 2 + 2 = 6

对于‘00100110’,该数组为2,1,2,2,1

所以答案是 1 + 1 + 2 + 1 = 5

代码

class Solution {
public int countBinarySubstrings(String s) {
int sum = 0;
// 只需要记录前一个不同元素的个数即可,不必保存所有个数
int prev = 0, cur = 1;
for (int i = 1; i < s.length(); ++i) {
if (s.charAt(i) == s.charAt(i - 1)) {
cur++;
} else {
if (prev != 0) sum += prev < cur ? prev : cur;
prev = cur;
cur = 1;
}
}
// 最后相邻的数要记得比较
return sum + (prev < cur ? prev : cur);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode