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.
此题难度不大,是基本的思路。右边字符是要匹配消掉的。左边是存入的!所以重点在右边字符!
bool isValid(string s) {
int i = 0;
int index = 0;
string right_str = ")}]";
string left_str = "({[";
stack<char> my_stack;
while(s[i] != '\0')
{
if((index=right_str.find(s[i])) >= 0)
{
if(my_stack.empty())
{
return false;
}
else
{
//另一种非索引方式
//if((my_stack.top() == '('&&s[i]==')')||(my_stack.top() == '{'&&s[i]=='}')||(my_stack.top() == '['&&s[i]==']'))
if(my_stack.top() == left_str[index])
my_stack.pop();
else
return false;
}
}
else
{
my_stack.push(s[i]);
}
i++;
}
return my_stack.empty();
}
本文介绍了一种用于判断括号字符串是否有效的算法,通过使用栈数据结构来匹配左右括号,确保它们按照正确的顺序关闭。
906

被折叠的 条评论
为什么被折叠?



