-
Notifications
You must be signed in to change notification settings - Fork 28
/
Valid_Parenthesis_String.cpp
106 lines (92 loc) · 3.06 KB
/
Valid_Parenthesis_String.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
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
// 3 ms
// can be done with stack instead of leftCount
class Solution {
bool checkValidString(int indx, string const& s, int leftCount, vector<vector<int>>& dp) {
if(indx == s.length()) {
return leftCount == 0;
}
if(dp[indx][leftCount] != -1) {
return dp[indx][leftCount];
}
if(s[indx] == '(') {
if(checkValidString(indx + 1, s, leftCount + 1, dp)) {
return dp[indx][leftCount] = true;
}
}
else if(s[indx] == '*') {
// empty
if(checkValidString(indx + 1, s, leftCount, dp)) {
return dp[indx][leftCount] = true;
}
// left parenthesis
if(checkValidString(indx + 1, s, leftCount + 1, dp)) {
return dp[indx][leftCount] = true;
}
// right parenthesis
if(leftCount > 0) {
if(checkValidString(indx + 1, s, leftCount - 1, dp)) {
return dp[indx][leftCount] = true;
}
}
}
else if(s[indx] == ')') {
if(leftCount > 0) {
if(checkValidString(indx + 1, s, leftCount - 1, dp)) {
return dp[indx][leftCount] = true;
}
}
}
return dp[indx][leftCount] = false;
}
public:
bool checkValidString(string s) {
vector<vector<int>> dp(s.length(), vector<int>(s.length() + 1, -1));
return checkValidString(0, s, 0, dp);
}
};
// 22 ms
// Solution: Sakibul Mowla
class Solution {
public:
vector<vector<int>> dp;
int checkValidString(string const& s, int strt, int endd) {
if (strt > endd) return true;
if (strt == endd) return s[strt] == '*';
int& ret = dp[strt][endd];
if (ret != -1) return ret;
if (s[strt] == '*') {
if(checkValidString(s, strt + 1, endd)) {
return ret = true;
}
if (s[endd] == '*' || s[endd] == ')')
if(checkValidString(s, strt + 1, endd - 1)) {
return ret = true;
}
}
if (s[endd] == '*') {
if(checkValidString(s, strt, endd - 1)) {
return ret = true;
}
if (s[strt] == '*' || s[strt] == '(')
if(checkValidString(s, strt + 1, endd - 1)) {
return ret = true;
}
}
if (s[strt] == '(' && s[endd] == ')') {
if(checkValidString(s, strt + 1, endd - 1)) {
return ret = true;
}
}
for (int k = strt; k < endd; k++) {
if(checkValidString(s, strt, k) && checkValidString(s, k + 1, endd)) {
return ret = true;
}
}
return ret = false;
}
bool checkValidString(string s) {
int n = s.size();
dp = vector<vector<int>> (n, vector<int> (n, -1));
return checkValidString(s, 0, n - 1);
}
};