Problem Description:
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.
题目大意:
给定一个字符串,判断它是否是一个合法的括号组。
Solutions:
经典的栈匹配的问题。仔细即可。
Code in C++:
class Solution {
public:
bool isValid(string s) {
stack<char>st;
for(int i = 0; i < s.length(); i ++)
{
switch(s[i]){
case '(':
case '[':
case '{': st.push(s[i]);break;
case ')':
if(st.empty()) return false;
if(st.top()!='(') return false;
else st.pop();
break;
case '}':
if(st.empty()) return false;
if(st.top()!='{') return false;
else st.pop();
break;
case ']':
if(st.empty()) return false;
if(st.top()!='[') return false;
else st.pop();
break;
default: continue;
}
}
return st.empty();
}
};
近期评论