forked from 20je0928/C-programs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Remove Invalid Parenthesis.cpp
69 lines (65 loc) · 1.38 KB
/
Remove Invalid Parenthesis.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
62
63
64
65
66
67
68
69
#include <iostream>
#include <queue>
#include <set>
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);
}
void removeInvalidParenthesis(string str)
{
if (str.empty()) {
return;
}
set<string> visit;
queue<string> q;
string temp;
bool level = false;
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()
{
cout << "\nEnter Parenthesis\t:\t";
string expression;
cin >> expression;
cout << "\nCorrect Parenthesis\t:\t";
removeInvalidParenthesis(expression);
return 0;
}