7-10 括号匹配(25 分) 【STL】

7-10 括号匹配(25 分)

给定一串字符,不超过100个字符,可能包括括号、数字、字母、标点符号、空格,编程检查这一串字符中的( ) ,[ ],{ }是否匹配。
输入格式:

输入在一行中给出一行字符串,不超过100个字符,可能包括括号、数字、字母、标点符号、空格。
输出格式:

如果括号配对,输出yes,否则输出no。
输入样例1:

sin(10+20)

输出样例1:

yes

输入样例2:

{[}]

输出样例2:

no

思路

用栈模拟 如果碰到是 左括号 就入栈
然后碰到 右括号 要判断 栈是不是空 如果空 就是不合法的

如果栈不空 那就要判断 栈顶 是不是对应的 左括号 如果不是 就不合法

AC代码

#include <cstdio>
#include <cstring>
#include <ctype.h>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <ctime>
#include <iostream>
#include <algorithm>
#include <deque>
#include <vector>
#include <queue>
#include <string>
#include <map>
#include <stack>
#include <set>
#include <numeric>
#include <sstream>
#include <iomanip>
#include <limits>

#define CLR(a) memset(a, 0, sizeof(a))
#define pb push_back

using namespace std;
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
typedef pair <int, int> pii;
typedef pair <ll, ll> pll;
typedef pair<string, int> psi;
typedef pair<string, string> pss;

const double PI = 3.14159265358979323846264338327;
const double E = exp(1);
const double eps = 1e-30;

const int INF = 0x3f3f3f3f;
const int maxn = 2e2 + 5;
const int MOD = 1e9 + 7;

int main()
{
    string s;
    getline(cin, s);
    int len = s.size();
    map <char, char> m;
    m['('] = ')';
    m['['] = ']';
    m['{'] = '}';
    stack <char> vis;
    int flag = 1;
    for (int i = 0; i < len; i++)
    {
        if (s[i] == '(' || s[i] == '[' || s[i] == '{')
            vis.push(s[i]);
        else if (s[i] == ')' || s[i] == ']' || s[i] == '}')
        {
            if (vis.size() && m[vis.top()] == s[i])
                vis.pop();
            else
            {
                flag = 0;
                break;
            }
        }
    }
    if (flag && vis.size() == 0)
        printf("yes
");
    else
        printf("no
");


}






原文地址:https://www.cnblogs.com/Dup4/p/9433194.html