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.
class Solution
{
public:
bool isValid(string s)
{
if (s == "")
return false;
int nSeqLen = s.length(),nstrForLen;
string strFor = "";//用字符串当成堆栈
if (nSeqLen % 2 != 0)//如果字符串长度为奇数则返回false
return false;
for (int nTemp = 0; nTemp < nSeqLen; nTemp++)//遍历输入字符串中的每一位
{
if (s[nTemp] == '{' || s[nTemp] == '[' || s[nTemp] == '(')//如果当前位符号为左边符号时则将符号入栈
strFor = strFor + s[nTemp];
else//如果当前位符号为右边符号时
{
nstrForLen = strFor.length();//读取当前堆栈的长度
if (nstrForLen == 0)//如果当前堆栈长度为0返回false
return false;
//如果当前位符号和堆栈中最后一位符号匹配则将堆栈中最后一位pop
if ((strFor[nstrForLen - 1] == '{'&&s[nTemp] == '}') || (strFor[nstrForLen - 1] == '['&&s[nTemp] == ']') || (strFor[nstrForLen - 1] == '('&&s[nTemp] == ')'))
{
strFor.pop_back();
}
else//如果不匹配则返回false
{
return false;
}
}
}
if (strFor != "")//如果字符串全部遍历后堆栈中还有符号则返回false
return false;
return true;
}
};