題目:
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.
題意:
給定一個字符串,裏面包含了’(‘, ‘)’, ‘{‘, ‘}’, ‘[’ , ‘]’。查看這個字符串是否是合法的。像這就是合法的,[(])就是不合法的。
思路:
使用棧存放符號,遇到左括號就入棧,遇到右括號就查看是否與棧頂的左括號相匹配。
代碼如下:
class Solution {
public:
bool isValid(string s) {
if(s.empty())return true;
stack<char> signs;
for(auto c : s) {
switch(c) {
case '(':signs.push(c);break;
case '[':signs.push(c);break;
case '{':signs.push(c);break;
case ')':{
if(signs.empty() || signs.top() != '(')return false;
signs.pop();
break;
}
case ']':{
if(signs.empty() || signs.top() != '[')return false;
signs.pop();
break;
}
case '}':{
if(signs.empty() || signs.top() != '{')return false;
signs.pop();
break;
}
}
}
return signs.empty();
}
};