Description
给一个长度不大于100的字符串,问该字符串里出现的括号是否合法。
字符串只会出现三种括号,“[]”,“()”,“{}”,且形如“({[]})”为合法,形如“[(])”为不合法。
Input
单组数据。
长度不大于100的字符串,字符串中不存在空格。
Output
如果该字符串中出现的所有括号都合法,输出“Yes”,否则输出“No”。
Sample Input
(a+b)!=c
Sample Output
Yes
Hint
#include <iostream>
#include <string.h>
using namespace std;
bool left(char c) //判断是否为左括号
{
if (c == '(' || c == '{' || c == '[')
{
return true;
}
return false;
}
bool right(char c) //判断是否为右括号
{
if (c == ')' || c == '}' || c == ']')
{
return true;
}
return false;
}
bool Whether_matche(char left, char right) //判断左右括号是否匹配
{
if (left == '(')
{
return (right == ')') ? true : false;
}
else if (left == '{')
{
return (right == '}') ? true : false;
}
else
return (right == ']') ? true : false;
}
int main()
{
char stack[200]; //存入左括号的栈
int top = 0; //栈顶
string s; //字符串
cin >> s;
int len = s.size();
for (int i = 0; i < len; i++)
{
if (left(s[i]))
{
stack[top++] = s[i]; //左括号入栈
}
else if (right(s[i]))
{
if (Whether_matche(stack[--top], s[i])) //左右括号开始匹配
{
continue; //如果匹配就继续循环
}
else
{
cout << "No"; //一旦出现不匹配的括号对就直接输出no
return 0;
}
}
else
{
continue;
}
}
if (!top)
{
cout << "Yes";
return 0;
}
cout << "No";
return 0;
}
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char buf[110], stk[110], stp;
bool Judge()
{
stp = -1;
for (int i = 0; buf[i]; i++)
switch (buf[i])
{
case '(':
stk[++stp] = ')';
break;
case '[':
stk[++stp] = ']';
break;
case '{':
stk[++stp] = '}';
break;
case ')':
case ']':
case '}':
if (stp == -1 || stk[stp] != buf[i])
return false;
else
stp--;
break;
}
return true;
}
int main()
{
while (scanf("%s", buf) != EOF)
printf(Judge() ? "Yes\n" : "No\n");
return 0;
}