在C ++中找到给定字符串中“ 1(0+)1”的所有模式

假设字符串的模式类似于1(0+)1。其中(0+)表示1s的非空连续出现。我们必须找到所有模式。模式可以重叠。该字符串不一定是二进制字符串。它只能容纳数字和小写字符。假设字符串像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