[LeetCode 20] Valid Parentheses Solution
2014-04-19 01:01
435 查看
Given a string containing just the characters
determine if the input string is valid.
The brackets must close in the correct order,
all valid but
not.
idea: go through the string. use a stack to store the '(''[''{'. then, if it is ')'']''}', check the stack.
The key of this question is how to use stack.
class Solution {
public:
bool isValid(string s) {
bool flag = false;
if(s.size() <= 1) return flag;
if(s.size() % 2 == 1) return flag;
stack <char> myStack;
for(int i = 0; i < s.size(); i++ ){
if(s[i] == '(' || s[i] == '[' || s[i] == '{'){
myStack.push(s[i]);
}else{
if(myStack.empty()) return false;
char back = myStack.top();
if(back == '('){
if(s[i] != ')') return false;
else myStack.pop();
}
else if(back == '['){
if(s[i] != ']') return false;
else myStack.pop();
}
else if(back == '{'){
if(s[i] != '}') return false;
else myStack.pop();
}
}
}
if(myStack.empty()) return true;
else return false;
}
};
'(',
')',
'{',
'}',
'['and
']',
determine if the input string is valid.
The brackets must close in the correct order,
"()"and
"()[]{}"are
all valid but
"(]"and
"([)]"are
not.
idea: go through the string. use a stack to store the '(''[''{'. then, if it is ')'']''}', check the stack.
The key of this question is how to use stack.
class Solution {
public:
bool isValid(string s) {
bool flag = false;
if(s.size() <= 1) return flag;
if(s.size() % 2 == 1) return flag;
stack <char> myStack;
for(int i = 0; i < s.size(); i++ ){
if(s[i] == '(' || s[i] == '[' || s[i] == '{'){
myStack.push(s[i]);
}else{
if(myStack.empty()) return false;
char back = myStack.top();
if(back == '('){
if(s[i] != ')') return false;
else myStack.pop();
}
else if(back == '['){
if(s[i] != ']') return false;
else myStack.pop();
}
else if(back == '{'){
if(s[i] != '}') return false;
else myStack.pop();
}
}
}
if(myStack.empty()) return true;
else return false;
}
};
相关文章推荐
- leetCode 20 Valid Parentheses
- leetcode 20. Valid Parentheses
- LeetCode 20 : Valid Parentheses (Java)
- [Leetcode] 20. Valid Parentheses(Stack)
- 【LeetCode】20 Valid Parentheses (c++实现)
- LeetCode20——Valid Parentheses
- [LeetCode]20. Valid Parentheses
- [leetcode 20] Valid Parentheses
- [leetcode]20. Valid Parentheses(java)
- LeetCode 20 Valid Parentheses
- [LeetCode]20.Valid Parentheses
- Leetcode20: Valid Parentheses
- leetcode题解-13. Roman to Integer && 14. Longest Common Prefix && 20. Valid Parentheses
- LeetCode 20 Valid Parentheses
- LeetCode(20) Valid Parentheses
- [LeetCode20]Valid Parentheses
- leetcode[20]:Valid Parentheses
- Leetcode 20 - Valid Parentheses
- [LeetCode] 20. Valid Parentheses
- leetcode:20. Valid Parentheses