
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find All Patterns of 1, 0+1 in a Given String in C++
Suppose a string has patterns like 1(0+)1. Where (0+) indicates non-empty consecutive occurrences of 1s. We have to find all of the patterns. The patterns can overlap. The string is not necessarily a binary string. It can hold digits and lowercase characters only. Suppose the string is like 1101001, then there are two such patterns. 101 and 1001.
To solve this problem, we will follow these steps −
Iterate through all character c in the string
When c is 1, then we iterate till the element is 0
When the stream of 0 ends, we will check whether the next character is 1 or not
These steps will be repeated until the end of string is reached.
Example
#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); }
Output
Number of substrings of pattern 1(0+)1 is: 4
Advertisements