678. Valid Parenthesis String
Given a string containing only three types of characters: ‘(’, ‘)’ and ‘*’, write a function to check whether this string is valid. We define the validity of a string by these rules:
Any left parenthesis ‘(’ must have a corresponding right parenthesis ‘)’.
Any right parenthesis ‘)’ must have a corresponding left parenthesis ‘(’.
Left parenthesis ‘(’ must go before the corresponding right parenthesis ‘)’.
‘*’ could be treated as a single right parenthesis ‘)’ or a single left parenthesis ‘(’ or an empty string.
An empty string is also valid.
Example 1:
Input: "()"
Output: True
Example 2:
Input: "(*)"
Output: True
Example 3:
Input: "(*))"
Output: True
Note:
- The string size will be in the range [1, 100].
方法1: two stacks
思路:
用一个栈来维护左括号,另一个维护* 的index, 如果栈空时可以启用count来用迄今为止累计的来继续抵消右括号,接替栈的作用。遍历至结尾需要连续pop出所有还剩下的左括号,用剩下的来match,并保证(出现在 *左边。最后*可以剩下但left不能剩。
class Solution {
public:
bool checkValidString(string s) {
stack<int> st_left;
stack<int> st_ast;
for (int i = 0; i < s.size(); i++) {
char c = s[i];
if (c == '(') {
st_left.push(i);
}
else if (c == '*') {
st_ast.push(i);
}
else if (c == ')') {
if (!st_left.empty()) {
st_left.pop();
}
else if (!st_ast.empty()){
st_ast.pop();
}
else return false;
}
}
while (!st_left.empty() && !st_ast.empty()) {
int left = st_left.top(); st_left.pop();
int ast = st_ast.top(); st_ast.pop();
if (ast < left) return false;
}
return st_left.empty();
}
};
方法2:
discussion: https://leetcode.com/problems/valid-parenthesis-string/discuss/107577/Short-Java-O(n)-time-O(1)-space-one-pass
grandyang:https://www.cnblogs.com/grandyang/p/7617017.html
思路:
discussion的高票答案,只需要 O(1) 空间。思路是每次遇到*,我们记录3中可能的岔路下可以达到的low和high,其中high表示* 被当成(继续累加,low表示被当成)用来抵消,保持最后我们只需要知道在众多支路的combination中有没有一条能够使得low和high的range covers 0. 那么对于high,每次遇到*不断累计,keep track of 上限,但是low没有必要取真的track下限,observe这个range始终是连续的,只需要知道能不能达到0,做了一些剪枝。每一次循环只要high<0了,说明即使全部变成“(”也比“)“要少的情况,立刻返回false。
class Solution {
public:
bool checkValidString(string s) {
int low = 0, high = 0;
for (char c: s) {
if (c == '(') {
high++;
low++;
}
else if (c == ')') {
if (low > 0) low--;
high --;
}
else if (c == '*') {
if (low > 0) low--;
high++;
}
if (high < 0) return false;
}
return low == 0;
}
};