给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。示例 1:
输入: “()”
输出: true
示例 2:输入: “()[]{}”
输出: true
示例 3:输入: “(]”
输出: false
示例 4:输入: “([)]”
输出: false
示例 5:输入: “{[]}”
输出: true
#include<iostream>
#include<stack>
using namespace std;
class Solution {
public:
bool isValid(string s) {
char character[6] = {'(', ')', '{', '}', '[', ']'};
stack<char> stk;
int lens = s.length();
if (lens == 0)
return true;
for (int i = 0; i < lens; i++)
{
if (s[i] == character[0] || s[i] == character[2] || s[i] == character[4])
stk.push(s[i]);
for(int j = 1; j < 6; j+=2 )
{
if (s[i] == character[j])
{
if (stk.empty())
return false;
char top = stk.top();
if (character[j-1] == top)
stk.pop();
else
return false;
}
}
}
if (stk.empty())
return true;
return false;
}
};
int main()
{
string str = "()[]{}";
Solution solution;
bool ans = solution.isValid(str);
cout << ans << endl;
return 0;
}