'('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.The brackets must close in the correct order,
"()"
and "()[]{}"
are all valid but "(]"
and "([)]"
are not.这题判断括号对,这种linear 往前看的,需要用到stack记录之前的状态,只有当stack的top和current element能匹配,stack才能pop出element,否则一直往里面加element,最后整个string遍历完,看stack里面是否为空,如果为空,说明完全匹配,否则不能完全匹配。
class Solution {
public:
bool isValid(string s) {
//sanity check
if (s.size() == 0) return true;
stack<char> buf;
for(int i = 0; i < s.size(); i++) {
if (buf.empty()) {
buf.push(s[i]);
continue;
}
if ((s[i] == ')' && buf.top() == '(') || (s[i] == '}' && buf.top() == '{') ||(s[i] == ']' && buf.top() == '[')) {
buf.pop();
}else buf.push(s[i]);
}
//to check if buf is empty
if (buf.empty()) return true;
else return false;
}
};
time complexity: O(n)
space complexity: O(1)
updated:
more shorter code, there are only one condition to pop from the stack, when the parentheses matches, in other conditions, just push into the stack
class Solution {
public:
bool isValid(string s) {
//sanity check
if(s.size() == 0) return true;
stack<char> buf;
for (int i = 0; i < s.size(); i++) {
if (!buf.empty() && (buf.top() == '{' && s[i] == '}' || (buf.top() == '[' && s[i] == ']') || (buf.top() == '(' && s[i] == ')')))
buf.pop();
else buf.push(s[i]);
}
if (buf.empty()) return true;
else return false;
}
};
No comments:
Post a Comment