Given a parentheses sequence; now, you have to print all the possible parentheses that it can make by removing the invalid brackets, for example
Input : str = “()())()” - Output : ()()() (())() There are two possible solutions "()()()" and "(())()" Input : str = (v)())() Output : (v)()() (v())()
In this question , we will use the backtracking method to print out all valid sequences.
In this method, we will try to remove open and closed brackets one by one using BFS. Now for each sequence we check if it is valid. If valid, print it as output.
#include <bits/stdc++.h> using namespace std; bool isParenthesis(char c){ return ((c == '(') || (c == ')')); } bool validString(string str){ // cout << str << " "; int cnt = 0; for (int i = 0; i < str.length(); i++){ if (str[i] == '(') cnt++; else if (str[i] == ')') cnt--; if (cnt < 0) return false; } // cout << str << " "; return (cnt == 0); } void validParenthesesSequences(string str){ if (str.empty()) return ; set<string> visit; // if we checked that sting so we put it inside visit // so that we will not encounter that string again queue<string> q; // queue for performing bfs string temp; bool level; // pushing given string as starting node into queue q.push(str); visit.insert(str); while (!q.empty()){ str = q.front(); q.pop(); if (validString(str)){ // cout << "s"; cout << str << "\n"; // we print our string level = true; // as we found the sting on the same level so we don't need to apply bfs from it } if (level) continue; for (int i = 0; i < str.length(); i++){ if (!isParenthesis(str[i])) // we won't be removing any other characters than the brackets from our string continue; temp = str.substr(0, i) + str.substr(i + 1); // removing parentheses from the strings one by one if (visit.find(temp) == visit.end()) { // if we check that string so we won't check it again q.push(temp); visit.insert(temp); } } } } int main(){ string s1; s1 = "(v)())()"; cout << "Input : " << s1 << "\n"; cout << "Output : "; validParenthesesSequences(s1); return 0; }
Input : (v)())() Output : (v())()
In the above method, we remove the brackets one by one, and we also track the previous sequence to avoid checking the same sequence twice. If we find a valid sequence, we print out all the valid possibilities, and this is how our program executes.
In this tutorial, we solved a problem of finding and removing invalid brackets. We also learned a C program to solve this problem and the complete solution (the common method). We can write the same program in other languages like C, Java, Python and others. Hope this tutorial is helpful to you.
The above is the detailed content of C++ remove invalid brackets from expression. For more information, please follow other related articles on the PHP Chinese website!