Skip to content

Commit 662dca4

Browse files
Adding 678-Valid-Parenthesis-String.c
1 parent 1972d20 commit 662dca4

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

c/678-Valid-Parenthesis-String.c

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/*
2+
Time: O(n)
3+
Space: O(1)
4+
*/
5+
6+
bool checkValidString(char * s) {
7+
int n = strlen(s);
8+
9+
int balanced = 0;
10+
for (int i=0; i<n; i++) {
11+
if (s[i] == '(' || s[i] == '*')
12+
balanced++;
13+
else
14+
balanced--;
15+
16+
if (balanced < 0)
17+
return false;
18+
}
19+
20+
if (balanced == 0)
21+
return true;
22+
23+
balanced = 0;
24+
for (int i=n-1; i>=0; i--) {
25+
if (s[i] == ')' || s[i] == '*')
26+
balanced++;
27+
else
28+
balanced--;
29+
30+
if (balanced < 0)
31+
return false;
32+
}
33+
34+
return true;
35+
}

0 commit comments

Comments
 (0)