Valid Parentheses
1,题目要求
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.
给定一个只包含字符’(’,’)’,’{’,’}’,’[‘和’]'的字符串,确定输入字符串是否有效。
如果输入字符串有效:
- 开放式支架必须用相同类型的支架封闭。
- 必须以正确的顺序关闭打开括号。
请注意,空字符串也被视为有效。
2,题目思路
这道题,是关于栈的应用操作。利用栈的先进后出的性质,来实现括号的匹配。
实现的思路不难,但是需要注意一些细节:
在判断部分,empty需要放在if前面,因为如果stack为空,取top会出错。因此,需要先对stack是否为空进行判断才行。
3,代码实现
int x = []() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
return 0;
}();
class Solution {
public:
bool isValid(string s) {
stack<char> bracket;
if(s.empty())
return true;
for(auto &c : s)
{
switch(c){
case '(':
case '[':
case '{': bracket.push(c);break;
case ')': if(bracket.empty() || bracket.top() != '(') return false; else bracket.pop();break;
case ']': if(bracket.empty() || bracket.top() != '[') return false; else bracket.pop();break;
case '}': if(bracket.empty() || bracket.top() != '{') return false; else bracket.pop();break;
default: break;
}
}
return bracket.empty();
}
};