two-pass greedy O(n) time O(1) space
反证即可,如果有反例则一定可以trap,否则就是balanced
There are 3 valid cases:
- There are more open parenthesis but we have enough ‘*‘ so we can balance the parenthesis with ‘)’
- There are more close parenthesis but we have enough ‘*‘ so we can balance the parenthesis with ‘(‘
- There are as many ‘(‘ than ‘)’ so all parenthesis are balanced, we can ignore the extra ‘*‘
Algorithm: You can parse the String twice, once from left to right by replacing all ‘*‘ by ‘(‘ and once from right to left by replacing all ‘*‘ by ‘)’. For each of the 2 loops, if there’s an iteration where you end up with a negative count (SUM[‘(‘] - SUM[‘)’] < 0) then you know the parenthesis were not balanced. You can return false. After these 2 checks (2 loops), you know the string is balanced because you’ve satisfied all the 3 valid cases mentioned above.
1 | class Solution { |
O(n) 用lo和hi来表示可能的左括号个数减右括号个数之差(只考虑非负数)的区间,
比如(*),(是[1, 1],(*是[0, 2],(*)是[0, 1]
1 | class Solution { |
1 | class Solution { |