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.
Example 1:
Input: "()" Output: true
Example 2:
Input: "()[]{}" Output: true
Example 3:
Input: "(]" Output: false
Example 4:
Input: "([)]" Output: false
Example 5:
Input: "{[]}" Output: true
题目翻译:
一个string的串,里边放了几种符号 [ ] ( ) { } 要求这些符号合理的组成括号。
需要考虑的边界值 :
[]) 返回false
“” 这种要返回 true
[](){} 这种要返回 true
解题思路:
这个思路很简单,使用stack即可,如果stack最上边的符号是(,而新进来的符号是 ) 这样可以弹出stack,括号不配对,就继续压栈。需要注意的是,如果stack是空的,那么stack.top()就会出错,所以,要在判断中加上 !stack.empty() 这样来确定是否出错。
#include <stack>
#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
bool isValid(string s) {
int n = s.length();
stack<char> sta;
for (int i = 0; i < n; i++)
{
if (s[i] == '}' && !sta.empty() && sta.top() == '{')
{
sta.pop();
continue;
}
if (s[i] == ']' && !sta.empty() && sta.top() == '[')
{
sta.pop();
continue;
}
if (s[i] == ')' && !sta.empty() && sta.top() == '(')
{
sta.pop();
continue;
}
sta.push(s[i]);
}
if (sta.empty())
return true;
else
return false;
}
};
int main()
{
string s;
getline(cin, s);
Solution so;
bool n = so.isValid(s);
cout << n << endl;
system("pause");
return 0;
}