volmodaoist / STUACM

STUACM专题笔记+提问答疑板块
6 stars 0 forks source link

UVa 673 - Parentheses Balance #6

Open caiyangyang711 opened 3 years ago

caiyangyang711 commented 3 years ago
#include<bits/stdc++.h>
using namespace std;

int main()
{

    int t;
    cin >> t;
    while (t--)
    {
        string s;
        stack<char>temp;
        cin >> s;
        for (int i = 0; i < s.size(); i++) {
            if (s[i] == '(' || s[i] == '[')
                temp.push(s[i]);
            else if (s[i] == ')') {
                if (temp.empty()) temp.push(s[i]);
                else {
                    if (temp.top() == '(')
                        temp.pop();
                    else temp.push(s[i]);
                }
            }

            else if (s[i] == ']') {
                if (temp.empty()) temp.push(s[i]);
                else {
                    if (temp.top() == '[')
                        temp.pop();
                    else temp.push(s[i]);
                }
            }
        }
        if (temp.empty()&&s.size()>=1)  cout << "Yes" << endl;
        else cout << "No" << endl;
    }
    return 0;
}

1 ` 2 3

volmodaoist commented 3 years ago

 getline 读取的是 string 类型,而在第一张图中的类型是字符数组,char-array、string两者是不一样的。string 类型才有 .size()方法。

  使用cin是没有办法读取空行的,因为cin在读取数字型数据的时候,会舍弃缓冲区中遇到的空白字符,包括空格、回车这些,而在cin读取字符串型数据的时候,又会以空白符作为截断点。因此,想要读取空行,要用getline函数。

  顺带一提,如果你用cin读完一个数据,紧接着用getline,大概率是会得到一个空字符串的。比如下面这种情况。此时 cin 读入kase之后,缓冲区当中还有一个回车符,那么接下来getline便会从缓冲区中读入的回车符,getline 不以空格作为截断点,而是以换行符作为截断点,因而会得到一个空字符串。(需要注意,空字符串不等于NULL,而是长度有效长度为零的字符串)

...
int kase;
int main(){
    cin>>kase;
    string ss;
    while(getline(cin,ss)){
         ...
    }
    return 0;
}
...