-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathInvalidParenthesis.java
95 lines (81 loc) · 1.93 KB
/
InvalidParenthesis.java
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package collectionz;
//Java program to remove invalid parenthesis
import java.util.*;
class InvalidParenthesis
{
//method checks if character is parenthesis(open
//or closed)
static boolean isParenthesis(char c)
{
return ((c == '(') || (c == ')'));
}
//method returns true if string contains valid
//parenthesis
static boolean isValidString(String str)
{
int cnt = 0;
for (int i = 0; i < str.length(); i++)
{
if (str.charAt(i) == '(')
cnt++;
else if (str.charAt(i) == ')')
cnt--;
if (cnt < 0)
return false;
}
return (cnt == 0);
}
//method to remove invalid parenthesis
static void removeInvalidParenthesis(String str)
{
if (str.isEmpty())
return;
// visit set to ignore already visited string
HashSet<String> visit = new HashSet<String>();
// queue to maintain BFS
Queue<String> q = new LinkedList<>();
String temp;
boolean level = false;
// pushing given string as
// starting node into queue
q.add(str);
visit.add(str);
while (!q.isEmpty())
{
str = q.peek();
q.remove();
if (isValidString(str))
{
System.out.println(str);
// If answer is found, make level true
// so that valid string of only that level
// are processed.
level = true;
}
if (level)
continue;
for (int i = 0; i < str.length(); i++)
{
if (!isParenthesis(str.charAt(i)))
continue;
// Removing parenthesis from str and
// pushing into queue,if not visited already
temp = str.substring(0, i) + str.substring(i + 1);
if (!visit.contains(temp))
{
q.add(temp);
visit.add(temp);
}
}
}
}
//Driver Code
public static void main(String[] args)
{
String expression = "()())()";
removeInvalidParenthesis(expression);
expression = "()v)";
removeInvalidParenthesis(expression);
}
}
//This code is contributed by 29AjayKumar