678. Valid Parenthesis String

Overview
There are three kind of characters in the string s
: '('
, ')'
and '*'
.
The asterisk '*'
can be use as '('
or ')'
.
Check if the string s
contains valid pairs of parentheses or not.
Solution 1: Stack
Algorithm
-
Initialize a list of
open_brackets
to store the indexes of open brackets.
Initialize a list ofasterisks
to store the indexes of asterisks. -
Iterate through string
s
:- If
char
is equal to'('
, appendindex
intoopen_brackets
. - If
char
is equal to'*'
, appendindex
intoasterisks
. - If
char
is equal to')'
, pop the index fromopen_brackets
orasterisks
. - Otherwise, return
false
.
There are not enough open brackets for the close bracket.
- If
-
If
open_brackets
andasterisks
are not empty:- Pop out
open_brackets
andasterisks
- If the index of the open bracket is greater than the index of the asterisk:
Returnfalse
, there are not enough close bracket after the open bracket.
- Pop out
-
Return
false
, ifopen_brackets
is not empty, as there still has some open brackets.
Otherwise, returntrue
.
Implement
class Solution: def checkValidString(self, s: str) -> bool: open_brackets: list[int] = [] asterisks: list[int] = [] for i, char in enumerate(s): if char == '(': open_brackets.append(i) elif char == '*': asterisks.append(i) else: # char == ')' if open_brackets: open_brackets.pop() elif asterisks: asterisks.pop() else: return False while open_brackets and asterisks: if open_brackets.pop() > asterisks.pop(): return False return not open_brackets
Complexity Analysis
Time complexity: O(n)
Iterating through string s
takes O(n) time.
Iterating through open_brackets
and asterisks
also takes O(n) time in the worst cases.
The total time complexity is O(2n), which simplifies to O(n).
Space complexity: O(n)
Using two additional list takes O(n) in the worst case scenario.