-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValidParentheses.java
More file actions
212 lines (170 loc) · 6.56 KB
/
ValidParentheses.java
File metadata and controls
212 lines (170 loc) · 6.56 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
package Algorithms.StackAlgos;
import java.util.HashMap;
import java.util.Stack;
import java.util.function.BiPredicate;
import java.util.function.Predicate;
/**
* @author Srinivas Vadige, srinivas.vadige@gmail.com
* @since 09 Jan 2025
* @link 20. Valid Parentheses <a href="https://leetcode.com/problems/valid-parentheses/">LeetCode link</a>
* @topics String, Stack
* @companies Amazon, Google, Meta, Bloomberg, Microsoft, Intuit, Apple, Oracle, DE Shaw, Yandex, LinkedIn, Roblox, AT&T, Walmart Labs, Visa, TikTok, Deloitte, EPAM Systems, Goldman Sachs, Wix, Turing, Adobe, BlackRock, Zoho, tcs, ServiceNow, Infosys, Uber, J.P. Morgan, Epic Systems
*/
public class ValidParentheses {
public static void main(String[] args) {
String s = "()[]{}";
System.out.println("isValid using Stack: " + isValidUsingStack(s));
System.out.println("isValid using Stack & HashMap: " + isValidUsingStackAndHashMap(s));
System.out.println("isValid using char array: " + isValidUsingCharArray(s));
}
public static boolean isValidUsingStack(String s) { // isValidUsingStack1
Stack<Character> stack = new Stack<>();
for(char c : s.toCharArray()) {
if (isOpen.test(c)) {
stack.push(c);
} else if (!stack.isEmpty() && isMatched.test(stack.peek(), c)) {
stack.pop();
} else { // stack empty
return false;
}
}
return stack.isEmpty();
}
static Predicate<Character> isOpen = c -> c == '(' || c == '{' || c == '[';
static BiPredicate<Character, Character> isMatched = (c1, c2) ->
c1 == '(' && c2 == ')' || c1 == '{' && c2 == '}' || c1 == '[' && c2 == ']';
// or
private static boolean isOpen(char c) {
return c == '(' || c == '{' || c == '[';
}
private static char getOpen(char closed) {
char open;
if (closed == ')') open = '(';
else if (closed == '}') open = '{';
else open = '[';
return open;
}
public static boolean isValidUsingStack2(String s) {
if (s.length() % 2 != 0) return false;
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) {
if (c == '(' || c == '{' || c == '[') stack.push(c);
else if (stack.isEmpty()) return false;
else if (c == ')' && stack.peek() == '(') stack.pop();
else if (c == '}' && stack.peek() == '{') stack.pop();
else if (c == ']' && stack.peek() == '[') stack.pop();
else return false;
}
return stack.isEmpty();
}
public boolean isValidUsingStack3(String s) {
if (s.length() % 2 != 0) return false;
Stack<Character> stack = new Stack<>();
for (int i=0; i<s.length(); i++) {
char c1 = s.charAt(i);
if (c1=='(' || c1=='{' || c1=='[') stack.push(c1);
else {
if (stack.empty()) return false;
char c2 = stack.pop();
if ( (c2 == '(' && c1 != ')') || (c2 == '{' && c1 != '}') || (c2 == '[' && c1 != ']') ) return false;
}
}
return stack.empty();
}
static HashMap<Character, Character> mappings = new HashMap<>() {{
put(')', '(');
put('}', '{');
put(']', '[');
}};
public static boolean isValidUsingStackAndHashMap(String s) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (mappings.containsKey(c)) {
if(stack.empty() || stack.pop()!=mappings.get(c)) {
return false;
}
} else {
stack.push(c);
}
}
return stack.isEmpty();
}
public static boolean isValidUsingCharArray(String s) {
if (s.length() % 2 != 0) return false;
char[] stack = new char[s.length()];
int i = 0; // head
for (char c : s.toCharArray()) {
switch (c) {
case '(':
case '{':
case '[':
stack[i++] = c;
break;
case ')':
if (i == 0 || stack[--i] != '(') return false;
break;
case '}':
if (i == 0 || stack[--i] != '{') return false;
break;
case ']':
if (i == 0 || stack[--i] != '[') return false;
break;
}
}
return i == 0;
}
/**
* NOT WORKING ❌ ---> This open & close count approach will only work with one single type of parenthesis
* test "([)]"
* here parenthesisOpen == parenthesisClose and squareOpen == squareClose but that's not the valid one
*
* @see #isValidUsingOpenCountOfSingleTypeNotWorking for more understanding ---> this is the intuition but it only works with one type of parenthesis
* close never exceeds open in valid parenthesis
*/
public static boolean isValidUsingOpenAndCloseCountsNotWorking(String s) {
int parenthesisOpen = 0;
int parenthesisClose = 0;
int curlyOpen = 0;
int curlyClose = 0;
int squareOpen = 0;
int squareClose = 0;
for (char c : s.toCharArray()) {
if (c == '(') {
parenthesisOpen++;
} else if (c == ')') {
parenthesisClose++;
} else if (c == '{') {
curlyOpen++;
} else if (c == '}') {
curlyClose++;
} else if (c == '[') {
squareOpen++;
} else if (c == ']') {
squareClose++;
}
if (parenthesisOpen < parenthesisClose || curlyOpen < curlyClose || squareOpen < squareClose) {
return false;
}
}
return parenthesisOpen == parenthesisClose && curlyOpen == curlyClose && squareOpen == squareClose;
}
/**
* We know that at any given point of time --- open >= close ---> i.e close never exceeds open
*/
private static boolean isValidUsingOpenCountOfSingleTypeNotWorking(String str) {
int open = 0;
int close = 0;
for (char c : str.toCharArray()) {
if (c == '(') {
open++;
} else {
close++;
}
if (open < close) { // or if(c==')') open--; and open < 0
return false;
}
}
return open == close; // or if(c==')') open--; and open == 0
}
}