题目描述
对于一行代码(字符串),里面可能出现大括号“{}”、中括号“[]”和小括号“()”,请编程判断改行代码的括号嵌套是否正确。
“()”,“({})”,“printf('Hello Netease')”等都是括号使用的正确方法,“(}”,"print(Hello Netease]"则是错误的范例。
输入描述
输入包含一行,为一行包含括号的字符串(字符串长度不超过1000)
输出描述
输出为true或者false
思路:
可以采用栈解题,对字符串进行遍历,每当遇到左括号,则push该左括号到栈中,若遇到右括号,则将栈顶的元素和其进行配对(注意判断栈是否为空),若为与之匹配的左括号,则pop该元素,否则输出false并return。
遍历结束后若栈不为空则输出false并return;
#include <iostream>
#include <string>
using namespace std;
const int STACK_CAPACITY = 128;
typedef char StackElement;
struct Stack
{
StackElement data[STACK_CAPACITY];
int top;
};
typedef Stack *StackPointer;
void Push(StackPointer stack, StackElement item)
{
stack->data[++(stack->top)] = item;
return;
}
void pop(StackPointer stack)
{
stack->top--;
}
int main()
{
int num = 0;
string str;
cin >> str;
StackPointer stack = (StackPointer)malloc(sizeof(Stack));
stack->top = -1;
for (int i = 0; i < str.size(); ++i)
{
if (str[i] == '(' || str[i] == '{' || str[i] == '[')
Push(stack, str[i]);
if (str[i] == ')')
{
if (stack->top != -1 && stack->data[stack->top] == '('){
num++;
pop(stack);
}
else{
cout << "false";
return 0;
}
}
else if (str[i] == ']')
{
if (stack->top != -1 && stack->data[stack->top] == '['){
num++;
pop(stack);
}
else{
cout << "false";
return 0;
}
}
else if (str[i] == '}')
{
if (stack->top != -1 && stack->data[stack->top] == '{'){
num++;
pop(stack);
}
else{
cout << "false";
return 0;
}
}
}
if (stack->top != -1)
{
cout << "false";
return 0;
}
cout << "true";
return 0;
}