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_bracketsto store the indexes of open brackets.
Initialize a list ofasterisksto store the indexes of asterisks. -
Iterate through string
s:- If
charis equal to'(', appendindexintoopen_brackets. - If
charis equal to'*', appendindexintoasterisks. - If
charis equal to')', pop the index fromopen_bracketsorasterisks. - Otherwise, return
false.
There are not enough open brackets for the close bracket.
- If
-
If
open_bracketsandasterisksare not empty:- Pop out
open_bracketsandasterisks - 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_bracketsis 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.