題目描述:
描述
現在,有一行括号序列,請你檢查這行括号是否配對。
輸入
第一行輸入一個數N(0<N<=100),表示有N組測試資料。後面的N行輸入多組輸入資料,每組輸入資料都是一個字元串S(S的長度小于10000,且S不是空串),測試資料組數少于5組。資料保證S中隻含有"[","]","(",")"四種字元
輸出
每組輸入資料的輸出占一行,如果該字元串中所含的括号是配對的,則輸出Yes,如果不配對則輸出No
樣例輸入
3
[(])
(])
([[]()])
樣例輸出
No
No
Yes
題目思路:
周遊字元串的每一個字元,如果是'['或者是'('則入棧;如果是']'或者')'并且棧頂是與之對應的'['或'('則不入棧并且彈出棧頂元素,否則也入棧。知道周遊完成,如果棧空,則比對成功,否則輸出"No";
題目代碼:
#include <string>
#include <iostream>
#include <stack>
using namespace std;
int n;
string s;
int main(){
cin>>n;
while(n--){
stack<char> st;
cin>>s;
for(int i = 0; i < s.length(); i++){
if(!st.empty() && ((s[i] == ']' && st.top() == '[') || (s[i] == ')' && st.top() == '('))){
st.pop();
}else{
st.push(s[i]);
}
}
if(st.empty())
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
}
return 0;
}