在 C++ 中找到给定字符串中所有“1(0+)1”的模式
假设一个字符串有类似 1(0+)1 的模式。其中 (0+) 表示连续出现且非空的 1。我们必须找到所有模式。这些模式可以重叠。该字符串不一定是二进制字符串。它只能包含数字和小写字符。假设该字符串类似 1101001,那么就有两种这样的模式。101 和 1001。
为了解决这个问题,我们将遵循以下步骤:
遍历字符串中的所有字符 c
当 c 为 1 时,我们遍历直到元素变成 0
当 0 的流结束时,我们将检查下一个字符是不是 1
在到达字符串末尾前一直重复这些步骤。
示例
#include<iostream>
using namespace std;
int countBinPattern(string main_str) {
char last_char = main_str[0];
int i = 1, counter = 0;
while (i < main_str.size()) {
if (main_str[i] == '0' && last_char == '1') {
while (main_str[i] == '0')
i++;
if (main_str[i] == '1')
counter++;
}
last_char = main_str[i];
i++;
}
return counter;
}
int main() {
string str = "10010110000101";
cout << "Number of substrings of pattern 1(0+)1 is: " << countBinPattern(str);
}输出
Number of substrings of pattern 1(0+)1 is: 4
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP