题目描述:LeetCode原题地址
Given a string containing just the characters ‘(’, ‘)’, ‘{’, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
解题思路: 用堆栈实现,遇到 ‘(’,’{’,’[’ 就进栈,遇到 ‘)’,’}’,’]’ 就出栈,最后如果堆栈为空,则说明全都是成功配对的。
代码一:
class Solution {
public:
bool isValid(string s) {
stack<char> parathese;
for(int i = 0; i < s.size(); i++){
if(s[i] == '(' || s[i] == '{' || s[i] == '['){
parathese.push(s[i]);
}else{
if(parathese.empty()){
return false;
}
if(s[i] == ')' && parathese.top() != '('){
return false;
}
if(s[i] == '}' && parathese.top() != '{'){
return false;
}
if(s[i] == ']' && parathese.top() != '['){
return false;
}
parathese.pop();
}
}
return parathese.empty();
}
};
代码二: LeetCode评论中的出现的代码
class Solution {
public:
bool isValid(string s) {
stack<char> paren;
for (char& c : s) {
switch (c) {
case '(':
case '{':
case '[': paren.push(c); break;
case ')': if (paren.empty() || paren.top()!='(') return false; else paren.pop(); break;
case '}': if (paren.empty() || paren.top()!='{') return false; else paren.pop(); break;
case ']': if (paren.empty() || paren.top()!='[') return false; else paren.pop(); break;
default: ; // pass
}
}
return paren.empty() ;
}
};