1.问题描述
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.
2.解题思路
这道题目其实非常简单,我们找一个类似于堆栈的数据结构保存每次得到的‘(’,‘[’,'{'三个字符,只要遇到这三个中的任意一种字符,就放入栈中。如果遇到‘)’、‘]’,'}'三个中的任意一个字符,就从堆栈弹出栈顶字符来比较是否匹配,如果匹配,则继续读取下一个数据,如果不匹配,则直接返回false。我的实现过程中采用一个string来充当堆栈,每次遇到‘)’、‘]’,'}'中的一种字符,则从字符串末尾读出一个字符进行比较,如果匹配,则删除字符串末尾的字符,继续读取下一个字符进行,如果不匹配,直接返回false。
3.代码实现
class Solution {
public:
//该函数判断两个字符是否匹配
bool isMatch(const char a, const char b)
{
if (a == '['&&b == ']')
return true;
else if (a == '('&&b == ')')
return true;
else if (a == '{'&&b == '}')
return true;
return false;
}
bool isValid(string s)
{
if (s == "")
return true;
string str("");
for (auto &e : s)
{
if (e != '}' && e != ']' && e != ')')
str += e;
else if (e == ')' || e == ']' || e == '}')
{
char x = str.back();
if (isMatch(x,e))
{
str.pop_back();
}
else
return false;
}
}
if (str == "")
return true;
else
return false;
}
};
4.运行结果