美文网首页
673 - Parentheses Balance

673 - Parentheses Balance

作者: 不会积 | 来源:发表于2017-04-04 20:59 被阅读0次

    题意就是输入一行包含()和[]的字符串,检查每对括号是否匹配得上,能就Yes否则No。
    然而题目好坑啊根本没说输入字符串里会含有空格,所以一开始用cin读取string总是蜜汁WA,调试了很久才发现得用getline,而且要注意一开始用cin读取一个整数n后,换行符会被cin忽略从而留在输入缓冲区里,下面getline碰到换行符就直接结束不读了,相当于多了一个空串。所以在cin完整数n后要再加一句getchar读取剩下的换行符。

    #include <iostream>
    #include <string>
    #include <stack>
    
    using namespace std;
    
    int main() {
        int n;
        cin >> n;
        getchar();
        for (int i = 0; i < n; i++) {
            string str;
            getline(cin, str);
            stack<char> s;
            for (int j = 0; j < str.length(); j++) {
                // 只有括号匹配的情况下才出栈
                if (str[j] == ')' && !s.empty() && s.top() == '(') {
                    s.pop();
                }
                else if (str[j] == ']' && !s.empty() && s.top() == '[') {
                    s.pop();
                }
                // 其余情况全部入栈
                else {
                    s.push(str[j]);
                }
            }
            // 如果所有的括号都匹配的话,栈肯定是空的
            if (s.empty())
                cout << "Yes" << endl;
            else
                cout << "No" << endl;
        }
        return 0;
    }
    

    相关文章

      网友评论

          本文标题:673 - Parentheses Balance

          本文链接:https://www.haomeiwen.com/subject/fbuzottx.html