Skip to content

Commit c9f36f8

Browse files
valid paranthesis
1 parent 9de00d1 commit c9f36f8

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed

week3/valid-paranthesis-string.cpp

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
// Probably bigger than it needs to be, but I'm feeling lazy !
2+
// Performance is also perfect so :shrug:
3+
4+
class Solution {
5+
public:
6+
bool checkValidString(string s) {
7+
return checkForward(s) && checkBack(s);
8+
}
9+
10+
bool checkForward(string s) {
11+
int opened = 0;
12+
int wildcards = 0;
13+
14+
for (string::iterator it = s.begin(); it != s.end(); ++it) {
15+
if (*it == '(') {
16+
++opened;
17+
}
18+
else if (*it == ')') {
19+
--opened;
20+
21+
while (opened < 0 && wildcards > 0) {
22+
++opened;
23+
--wildcards;
24+
}
25+
26+
if (opened < 0) {
27+
return false;
28+
}
29+
} else if (*it == '*') {
30+
++wildcards;
31+
}
32+
}
33+
34+
if (opened == 0 || abs(opened) <= wildcards) {
35+
return true;
36+
}
37+
38+
return false;
39+
}
40+
41+
bool checkBack(string s) {
42+
int closed = 0;
43+
int wildcards = 0;
44+
45+
for (string::reverse_iterator it = s.rbegin(); it != s.rend(); ++it) {
46+
if (*it == ')') {
47+
++closed;
48+
}
49+
else if (*it == '(') {
50+
--closed;
51+
52+
while (closed < 0 && wildcards > 0) {
53+
++closed;
54+
--wildcards;
55+
}
56+
57+
if (closed < 0) {
58+
return false;
59+
}
60+
} else if (*it == '*') {
61+
++wildcards;
62+
}
63+
}
64+
65+
if (closed == 0 || abs(closed) <= wildcards) {
66+
return true;
67+
}
68+
69+
return false;
70+
}
71+
};

0 commit comments

Comments
 (0)