括号匹配

2019-11-27  本文已影响0人  鹿与云与雨

检查一段C语言代码的小括号( )、 中括号 [ ] 和大括号{ } 是否匹配。

//有部分测试未通过
#include <iostream>
#include<string>
#include<stack>
#include<cstring>
using namespace std;

int main()
{
    int j, i = 0, k = 0;
    stack<char>s;
    string a;
    getline(cin, a);
    for (j = 0; j < a.length(); j++)
    {
        if (a[j] == '(' || a[j] == '{' || a[j] == '[')
        {
            s.push(a[j]);
            i = i + 1;
        }
        if (a[j] == ')')
        {
            k = k + 1;
            if (s.top() == '(')
                s.pop();
            else
                continue;
        }
        if (a[j] == '}')
        {
            k = k + 1;
            if (s.top() == '{')
                s.pop();
            else
                continue;
        }
        if (a[j] == ']')
        {
            k = k + 1;
            if (s.top() == '[')
                s.pop();
            else
                continue;
        }
    }
    cout << i << " " << k << endl;
    if (s.empty() == 1)
        cout << "YES";
    else cout << "NO";
    return 0;
}
上一篇 下一篇

猜你喜欢

热点阅读