问题:
利用程序判断字符串中的括号是否匹配
[()],左右括号出现在对应位置则匹配,反之则不匹配
思路:
利用栈后进先出的特点
0.从左自右遍历字符串
1.遇到左括号时,将左括号压入栈中
2.遇到右括号时,先判断栈是否为空,
2.1若为空,则括号不匹配,右括号过多
2.2若不为空,判断栈顶元素是否和左括号匹配
3.当字符串遍历结束时,判断栈是否为空
3.1若为空,则括号匹配
3.2若不为空,则左括号过多,括号不匹配
代码:
int main()
{
if (blackMatch("{[()]}"))
cout << "匹配正确";
else
cout << "匹配错误";
cout << endl;
system("pause");
}
bool blackMatch(const string &str)
{
stack<char> s;
for (int i = 0; i < str.length(); i++)
{
if (str[i] == '(' || str[i] == '[' || str[i] == '{')
{
s.push(str[i]);
}
else if (str[i] == ')' || str[i] == ']' || str[i] == '}')
{
if (s.empty())
return false;
else
{
if (match(str[i], s))
s.pop();
else
return false;
}
}
}
if (!s.empty())
return false;
return true;
}
bool match(const char c, const stack<char> &s)
{
if (c == ')')
return s.top() == '(';
else if (c == ']')
return s.top() == '[';
else if (c == '}')
return s.top() == '{';
}