leetcode 696. Count Binary Substrings
来源:互联网 发布:linux :wq没有保存退出 编辑:程序博客网 时间:2024/05/21 13:23
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.
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.
以发现我们只要分别统计0和1的个数,而且如果当前遇到的是1,那么只要之前统计的0的个数大于当前1的个数,就一定有一个对应的子字符串,而一旦前一个数字和当前的数字不一样的时候,那么当前数字的计数要重置为1。所以我们遍历元数组,如果是第一个数字,那么对应的ones或zeros自增1。然后进行分情况讨论,如果当前数字是1,然后判断如果前面的数字也是1,则ones自增1,否则ones重置为1。如果此时zeros大于ones,res自增1。反之同理,如果当前数字是0,然后判断如果前面的数字也是0,则zeros自增1,否则zeros重置为1。如果此时ones大于zeros,res自增1。
代码如下:
#include <iostream>#include <vector>#include <map>#include <set>#include <queue>#include <stack>#include <string>#include <climits>#include <algorithm>#include <sstream>#include <functional>#include <bitset>#include <numeric>#include <cmath>#include <regex>using namespace std;class Solution {public: int countBinarySubstrings(string s) { int res = 0, count0 = 0, count1 = 0; for (int i = 0; i < s.length(); i++) { if (i == 0) (s[i] == '1') ? count1++ : count0++; else { if (s[i] == '1') { count1 = s[i - 1] == s[i] ? count1 + 1 : 1; if (count0 >= count1) res++; }else { count0 = s[i - 1] == s[i] ? count0 + 1 : 1; if (count1 >= count0) res++; } } } return res; }};
- leetcode 696. Count Binary Substrings
- leetcode-696. Count Binary Substrings
- leetcode 696. Count Binary Substrings
- leetcode 696. Count Binary Substrings
- Count Binary Substrings(leetcode)
- leetcode题解-696. Count Binary Substrings
- 696. Count Binary Substrings
- 696. Count Binary Substrings
- 696. Count Binary Substrings
- 696. Count Binary Substrings
- leetcode 696 Count Binary Substrings
- LeetCode-Easy-Java-Count Binary Substrings
- LeetCode之Count Binary Substrings(Kotlin)
- LWC 54:696. Count Binary Substrings
- python--leetcode696. Count Binary Substrings
- Count Binary Substrings问题及解法
- Codechef Count Substrings
- 451 D. Count Good Substrings
- Comparable与Comparator的具体应用场景
- RMI简单示例
- 【LDA】LDA主题模型
- 发布uap项目
- 3年工作经验的程序员应该具备的技能
- leetcode 696. Count Binary Substrings
- JPA一对多关系
- 分布式一致性系统的动态替换实现机制
- Linux chmod授权命令说明
- Memory Tracker原理分析
- 数据模型深入解释
- 平衡树学习笔记(1) BST
- 守护进程
- 程序员的幽默你不懂