南陽括號匹配

括號配對問題

時間限制:3000 ms  |  內存限制:65535 KB
難度:3
描述
現在,有一行括號序列,請你檢查這行括號是否配對。
輸入
第一行輸入一個數N(0<N<=100),表示有N組測試數據。後面的N行輸入多組輸入數據,每組輸入數據都是一個字符串S(S的長度小於10000,且S不是空串),測試數據組數少於5組。數據保證S中只含有"[","]","(",")"四種字符
輸出
每組輸入數據的輸出佔一行,如果該字符串中所含的括號是配對的,則輸出Yes,如果不配對則輸出No
樣例輸入
3
[(])
(])
([[]()])
樣例輸出
No
No
Yes
來源
網絡
上傳者

naonao

模擬棧。。。。。

風格一:

STL、、、

/*#include<iostream>
#include<cstdio>
#include<stack>
#include<cstring>
#include<algorithm>
using namespace std;
int main()
{
    char str[10001];
    int t;
    cin>>t;
    int flag;
    while(t--)
    {
        flag=1;
        stack<char>st;
        cin>>str;
        for(int i=0;i<strlen(str);i++)
        {
            if(str[i]=='['||str[i]=='(')
                st.push(str[i]);
            else if(str[i]==']')
            {
                if(st.top()!='['||st.empty())
                {
                    flag=0;
                }
                else st.pop();
            }
            else if(str[i]==')')
            {
                if(st.top()!='('||st.empty())
                flag=0;
                else st.pop();
            }
        }
        if(!st.empty()) flag=0;
        if(flag) printf("Yes\n");
        else printf("No\n");
    }
    return 0;
}
*/
風格二、、STL

#include <iostream>
#include <stack>
#include <string>
using namespace std;

int main()
{
	int N;
	cin>>N;
	while(N--)
	{
		string a;
		stack<char> s;
		cin>>a;
		for(int i=0;i<a.size();i++)
		{
			if(a[i]=='('||a[i]=='[')
				s.push(a[i]);
			else if(a[i]==')')
			{
				if(!s.empty()&&s.top()=='(')
					s.pop();
				//else
					//s.push(a[i]);
			}
			else if(a[i]==']')
			{
				if(!s.empty()&&s.top()=='[')
					s.pop();
				//else
					//s.push(a[i]);
			}
		}
		if(s.empty())
			cout<<"Yes"<<endl;
		else
			cout<<"No"<<endl;
	}
	return 0;
}
風格三:

、、、

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章