forked from Debraj-Kundu/All-Leetcode-Questions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
removeinvalidparenthisis.cpp
61 lines (54 loc) · 1.1 KB
/
removeinvalidparenthisis.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/* C/C++ program to remove invalid parenthesis */
#include <bits/stdc++.h>
using namespace std;
bool isParenthesis(char c){
return ((c == '(') || (c == ')'));
}
bool isValidString(string 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;
}
return (cnt == 0);
}
// method to remove invalid parenthesis
void removeInvalidParenthesis(string str){
if (str.empty())
return ;
set<string> visit;
queue<string> q;
string temp;
bool level;
q.push(str);
visit.insert(str);
while (!q.empty()){
str = q.front(); q.pop();
if (isValidString(str)){
cout << str << endl;
level = true;
}
if (level)
continue;
for (int i = 0; i < str.length(); i++){
if (!isParenthesis(str[i]))
continue;
temp = str.substr(0, i) + str.substr(i + 1);
if (visit.find(temp) == visit.end()){
q.push(temp);
visit.insert(temp);
}
}
}
}
int main(){
string expression = "()())()";
removeInvalidParenthesis(expression);
expression = "()v)";
removeInvalidParenthesis(expression);
return 0;
}