您的位置:首页 > 其它

[LeetCode 20] Valid Parentheses Solution

2014-04-19 01:01 435 查看
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.

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 stack