【leetcode】ValidParentheses
Question :
Given a string containing just the characters
'('
,
')'
,
'{'
,
'}'
,
'['
and
']'
, determine if the input string is valid.
The brackets must close in the correct order,
"()"
and
"()[]{}"
are all valid but
"(]"
and
"([)]"
are not.
Anwser 1 :
Stack
class Solution {
public:
bool isValid(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
stack<char> st;
for(int i = 0; i < s.size(); i++)
{
if(s[i] == '(' || s[i] == '{' || s[i] == '['){
st.push(s[i]);
}
if(s[i] == ')')
{
if(st.empty() || st.top() != '(')
return false;
st.pop();
}
if(s[i] == '}')
{
if(st.empty() || st.top() != '{')
return false;
st.pop();
}
if(s[i] == ']')
{
if(st.empty() || st.top() != '[')
return false;
st.pop();
}
}
if(st.empty() == 0)
return false;
return true;
}
};
Anwser 2 :
class Solution {
public:
bool isValid(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
stack<char> st;
for (int i = 0; i < s.size(); i++) {
char c = s[i];
if (isLeft(c)) { // push
st.push(c);
} else {
if (st.empty()) {
return false;
}
char d = st.top(); // pop
st.pop();
if (!match(d, c)) {
return false;
}
}
}
if (st.empty()) {
return true;
}
else {
return false;
}
}
bool isLeft(char c) {
return c == '{' || c == '[' || c == '(';
}
bool match(char c, char d) {
return (c == '(' && d == ')') || (c == '[' && d == ']') || (c == '{' && d == '}');
}
};
版权所有: 本文系米扑博客原创、转载、摘录,或修订后发表,最后更新于 2013-05-01 20:07:10
侵权处理: 本个人博客,不盈利,若侵犯了您的作品权,请联系博主删除,莫恶意,索钱财,感谢!