括号匹配问题会出现以下几种场景:
①左括号多于右括号
②右括号多于左括号
③括号类型不匹配
④括号匹配成功
首先,我们要考虑几个问题:
①遇到不是括号的字符,应该向后走;
②从前往后遍历,遇到左括号,入栈;
③遇到右括号,和栈顶元素匹配,看是否匹配成功,若这时栈为空,说明左括号少于右括号,若不匹配,则输出提示信息,j结束函数,若匹配,则栈顶元素出栈,继续向后走。
④若遍历到最后一个字符,栈仍不为空,则数明左括号多于右括号,否则,匹配成功。
bool MatchBrackets(char* str, size_t size)
{
stack<char> s;
for (size_t i = 0; i < size; i++)
{
//不是括号的字符
if (str[i] != '{' && str[i] != '(' && str[i] != '['
&& str[i] != '}' && str[i] != ')' && str[i] != ']')
{
continue;
}
else
{
//左括号
if (str[i] == '{' || str[i] == '(' || str[i] == '[')
{
s.push(str[i]);
continue;
}
//右括号
else
{
if (s.empty())
{
cout << "右括号比左括号多!" << endl;
return false;
}
char top = s.top();
if (top == '{'&&str[i] == '}' ||
top == '('&&str[i] == ')' ||
top == '['&&str[i] == ']')
{
s.pop();
continue;
}
cout << "括号不匹配!"<<endl;
return false;
}
}
}
if (!s.empty())
{
cout << "左括号比右括号多!" << endl;
return false;
}
cout << "括号匹配成功!" << endl;
return true;
}
测试函数:
int main()
{
char arr1[] = "((())abc{[]}";
char arr2[] = "{}{}((abc))))";
char arr3[] = "({)}()abc{}";
char arr4[] = "()()abc{}([()])";
MatchBrackets(arr1, sizeof(arr1) / sizeof(arr1[0]));
MatchBrackets(arr2, sizeof(arr2) / sizeof(arr2[0]));
MatchBrackets(arr3, sizeof(arr3)/sizeof(arr3[0]));
MatchBrackets(arr4, sizeof(arr4) / sizeof(arr4[0]));
system("pause:");
return 0;
}