forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_678.java
97 lines (92 loc) · 3.3 KB
/
_678.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
package com.fishercoder.solutions;
import java.util.Stack;
public class _678 {
public static class Solution1 {
/**
* This solution is correct, but will result in TLE by test4
*/
public boolean checkValidString(String s) {
if (!s.contains("*")) {
Stack<Character> stack = new Stack();
int i = 0;
while (i < s.length()) {
if (s.charAt(i) == '(') {
stack.push(s.charAt(i));
} else {
if (stack.isEmpty()) {
return false;
} else {
stack.pop();
}
}
i++;
}
return stack.isEmpty();
} else {
int index = s.indexOf("*");
String transformedS = s.substring(0, index) + s.substring(index + 1);
if (checkValidString(transformedS)) {
return true;
}
transformedS = s.substring(0, index) + "(" + s.substring(index + 1);
if (checkValidString(transformedS)) {
return true;
}
transformedS = s.substring(0, index) + ")" + s.substring(index + 1);
if (checkValidString(transformedS)) {
return true;
}
}
return false;
}
}
public static class Solution2 {
public boolean checkValidString(String s) {
return isValid(s, 0, 0);
}
private boolean isValid(String s, int start, int cnt) {
if (cnt < 0) {
return false;
}
for (int i = start; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '(') {
cnt++;
} else if (c == ')') {
if (cnt <= 0) {
return false;
}
cnt--;
} else if (c == '*') {
/**Extra caution: start should be i+1, not start+1 !*/
return isValid(s, i + 1, cnt + 1)
|| isValid(s, i + 1, cnt - 1)
|| isValid(s, i + 1, cnt);
}
}
return cnt == 0;
}
}
public static class Solution3 {
/**
* Greedy solution:
* 1. Let lo mean the lowest possible open left paren
* 2. Let hi mean the possibilities of highest possible open left paren, so as long as s.charAt(i) != ')', it's possible to be a '(', so we'll increment hi by 1
* 2. If at any time, hi becomes negative, that means this string will never be valid
* 3. Each time, we'll let lo be at a minimum of zero
*/
public boolean checkValidString(String s) {
int lo = 0;
int hi = 0;
for (int i = 0; i < s.length(); i++) {
lo += s.charAt(i) == '(' ? 1 : -1;
hi += s.charAt(i) != ')' ? 1 : -1;
if (hi < 0) {
break;
}
lo = Math.max(0, lo);
}
return lo == 0;
}
}
}