Given a binary string str, the task is to check whether the given string follows the below condition or not:
- String starts with a ‘1’.
- Each ‘1’ is followed by empty string(“”), ‘1’, or “00”.
- Each “00” is followed by empty string(“”), ‘1’.
If the given string follows the above criteria then print “Valid String” else print “Invalid String”.
Input: str = “1000”
The given string starts with “1” and has “00” followed by the “1” which is not the given criteria.
Hence, the given string is “Invalid String”.
Input: str = “1111”
The given string starts with 1 and has 1 followed by all the 1’s.
Hence, the given string is “Valid String”.
Approach: The idea is to use Recursion. Below are thes steps:
- Check whether 0th character is ‘1’ or not. If it is not ‘1’, return false as the string is not following condition 1.
- To check string satisfying the second condition, recursively call for string starting from 1st index using substr() function in C++.
- To check string satisfying the third condition, first, we need to check if the string length is greater than 2 or not. If yes, then check if ‘0’ is present at the first and second index. If yes, then recursively call for the string starting from 3rd index.
- At any recursive call, If the string is empty, then we have traversed complete string satisfying all the given conditions and print “Valid String”.
- At any recursive call, If the given condition doesn’t satisfy then stop that recursion and print “Invalid String”.
Below is the implementation of the above approach:
Time Complexity: O(N), where N is the length of string.
Auxiliary Space: O(1).
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.