-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathValidParenthesisString.java
369 lines (333 loc) · 10.5 KB
/
ValidParenthesisString.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
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
package LeetCodeJava.String;
// https://leetcode.com/problems/valid-parenthesis-string/description/
import java.util.Stack;
/**
* 678. Valid Parenthesis String
* Medium
* Topics
* Companies
* Hint
* Given a string s containing only three types of characters: '(', ')' and '*', return true if s is valid.
*
* The following rules define a valid string:
*
* Any left parenthesis '(' must have a corresponding right parenthesis ')'.
* Any right parenthesis ')' must have a corresponding left parenthesis '('.
* Left parenthesis '(' must go before the corresponding right parenthesis ')'.
* '*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string "".
*
*
* Example 1:
*
* Input: s = "()"
* Output: true
* Example 2:
*
* Input: s = "(*)"
* Output: true
* Example 3:
*
* Input: s = "(*))"
* Output: true
*
*
* Constraints:
*
* 1 <= s.length <= 100
* s[i] is '(', ')' or '*'.
*
*/
public class ValidParenthesisString {
// V0
// IDEA: GREEDY
// https://neetcode.io/problems/valid-parenthesis-string
/**
* IDEA 1) GREEDY
*
* step 1) maintain 2 var
* - minParenCnt
* - bigParenCnt
*
* step 2) within loop
* - if "(", minParenCnt += 1, bigParenCnt += 1
* - if ")", minParenCnt -= 1, bigParenCnt -= 1
* - if "*", `wild card`
* - minParenCnt -= 1
* - bigParenCnt += 1
* - NOTE !!
* - if minParenCnt < 0, we reset it as 0
* - if bigParenCnt < 0, return false directly
*
* step 3) check if 0 == minParenCnt
*
*/
public boolean checkValidString(String s) {
// edge
if(s == null || s.isEmpty()){
return true;
}
if(s.length() == 1){
return s.equals("*"); // only "*", return true, otherwise return false
}
/** NOTE !!!
*
* we init, maintain 2 var:
*
* (consider there are 3 possible cases of `wild card` "*"
* -> e.g. "*" can be either ")" or "(" or ""
*
* - minParenCnt
* - maxParenCnt
*/
int minParenCnt = 0;
int maxParenCnt = 0;
for(String x: s.split("")){
if(x.equals("(")){
minParenCnt += 1;
maxParenCnt += 1;
}
else if(x.equals(")")){
minParenCnt -= 1;
maxParenCnt -= 1;
}else{
minParenCnt -= 1;
maxParenCnt += 1;
}
// NOTE !!! below
/** NOTE !!!
*
* 1) if minParenCnt < 0, reset it as 0,
* since it's possible to `keep 0 for minParenCnt`
*
* 2) if maxParenCnt < 0, reset false directly,
* since it does NOT make sense to use negative val as maxParenCnt
*/
if(minParenCnt < 0){
minParenCnt = 0;
}
if(maxParenCnt < 0){
return false;
}
}
return minParenCnt == 0; // ???
}
// V1-1
// https://neetcode.io/problems/valid-parenthesis-string
// IDEA: RECURSION
public boolean checkValidString_1_1(String s) {
return dfs(0, 0, s);
}
private boolean dfs(int i, int open, String s) {
if (open < 0) return false;
if (i == s.length()) return open == 0;
if (s.charAt(i) == '(') {
return dfs(i + 1, open + 1, s);
} else if (s.charAt(i) == ')') {
return dfs(i + 1, open - 1, s);
} else {
return dfs(i + 1, open, s) ||
dfs(i + 1, open + 1, s) ||
dfs(i + 1, open - 1, s);
}
}
// V1-2
// https://neetcode.io/problems/valid-parenthesis-string
// IDEA: DP (TOP DOWN)
public boolean checkValidString_1_2(String s) {
int n = s.length();
Boolean[][] memo = new Boolean[n + 1][n + 1];
return dfs(0, 0, s, memo);
}
private boolean dfs(int i, int open, String s, Boolean[][] memo) {
if (open < 0) return false;
if (i == s.length()) return open == 0;
if (memo[i][open] != null) return memo[i][open];
boolean result;
if (s.charAt(i) == '(') {
result = dfs(i + 1, open + 1, s, memo);
} else if (s.charAt(i) == ')') {
result = dfs(i + 1, open - 1, s, memo);
} else {
result = (dfs(i + 1, open, s, memo) ||
dfs(i + 1, open + 1, s, memo) ||
dfs(i + 1, open - 1, s, memo));
}
memo[i][open] = result;
return result;
}
// V1-3
// https://neetcode.io/problems/valid-parenthesis-string
// IDEA: DP (BOTTOM UP)
public boolean checkValidString_1_3(String s) {
int n = s.length();
boolean[][] dp = new boolean[n + 1][n + 1];
dp[n][0] = true;
for (int i = n - 1; i >= 0; i--) {
for (int open = 0; open < n; open++) {
boolean res = false;
if (s.charAt(i) == '*') {
res |= dp[i + 1][open + 1];
if (open > 0) res |= dp[i + 1][open - 1];
res |= dp[i + 1][open];
} else {
if (s.charAt(i) == '(') {
res |= dp[i + 1][open + 1];
} else if (open > 0) {
res |= dp[i + 1][open - 1];
}
}
dp[i][open] = res;
}
}
return dp[0][0];
}
// V1-4
// https:/neetcode.io/problems/valid-parenthesis-string
// IDEA: DP (SPACE OPTIMIZED)
public boolean checkValidString_1_4(String s) {
int n = s.length();
boolean[] dp = new boolean[n + 1];
dp[0] = true;
for (int i = n - 1; i >= 0; i--) {
boolean[] newDp = new boolean[n + 1];
for (int open = 0; open < n; open++) {
if (s.charAt(i) == '*') {
newDp[open] = dp[open + 1] ||
(open > 0 && dp[open - 1]) || dp[open];
} else if (s.charAt(i) == '(') {
newDp[open] = dp[open + 1];
} else if (open > 0) {
newDp[open] = dp[open - 1];
}
}
dp = newDp;
}
return dp[0];
}
// V1-5
// https://neetcode.io/problems/valid-parenthesis-string
// IDEA: STACK
public boolean checkValidString_1_5(String s) {
Stack<Integer> left = new Stack<>();
Stack<Integer> star = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch == '(') {
left.push(i);
} else if (ch == '*') {
star.push(i);
} else {
if (left.isEmpty() && star.isEmpty()) return false;
if (!left.isEmpty()) {
left.pop();
} else{
star.pop();
}
}
}
while (!left.isEmpty() && !star.isEmpty()) {
if (left.pop() > star.pop())
return false;
}
return left.isEmpty();
}
// V1-6
// https://neetcode.io/problems/valid-parenthesis-string
// IDEA: GREEDY
public boolean checkValidString_1_6(String s) {
int leftMin = 0, leftMax = 0;
for (char c : s.toCharArray()) {
if (c == '(') {
leftMin++;
leftMax++;
} else if (c == ')') {
leftMin--;
leftMax--;
} else {
leftMin--;
leftMax++;
}
if (leftMax < 0) {
return false;
}
if (leftMin < 0) {
leftMin = 0;
}
}
return leftMin == 0;
}
// V2
// IDEA: GREEDY (fixed by gpt)
/**
* We can approach the solution with a greedy method that counts the number of open parentheses ( and ensures that the number of * can balance the parentheses. We'll perform two passes:
*
* 1) Left-to-right pass:
* Count ( and * to ensure that we don't have more )
* than we can potentially balance.
*
* 2) Right-to-left pass:
* Count ) and * to ensure that we don't have more
* ( than we can balance with *.
*
*
* Explanation:
*
* 1) Left-to-right pass:
* We check if the number of ) ever exceeds (.
* If it does, we attempt to use a * as an opening parenthesis.
*
*
*
* 2) Right-to-left pass: Similarly, we check
* if the number of ( exceeds ) and use * as a closing
* parenthesis if needed.
*
*/
public boolean checkValidString_2(String s) {
// Left to right pass
int leftBalance = 0;
int starCount = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '(') {
leftBalance++;
} else if (c == ')') {
leftBalance--;
} else { // c == '*'
starCount++;
}
// If at any point we have more ')' than '(', then it's invalid
if (leftBalance < 0) {
if (starCount > 0) {
leftBalance++; // Treat a '*' as an open parenthesis '('
starCount--; // Use one star as '('
} else {
return false;
}
}
}
// Right to left pass
int rightBalance = 0;
starCount = 0; // Reset star count for the second pass
for (int i = s.length() - 1; i >= 0; i--) {
char c = s.charAt(i);
if (c == ')') {
rightBalance++;
} else if (c == '(') {
rightBalance--;
} else { // c == '*'
starCount++;
}
// If at any point we have more '(' than ')', then it's invalid
if (rightBalance < 0) {
if (starCount > 0) {
rightBalance++; // Treat a '*' as a closing parenthesis ')'
starCount--; // Use one star as ')'
} else {
return false;
}
}
}
return true; // If we passed both passes, the string is valid
}
}