竹園論壇

標題: 673 - Parentheses Balance [打印本頁]

作者: HSCHE    時間: 2014-5-2 12:41
標題: 673 - Parentheses Balance
在本題中,題目會先給你一個包含小括號()及中括號〔〕的字串。當字串符合下列條件時我們稱他為正確的運算式:
現在,請你寫一支程式可以讀入這類字串並檢查它們是否為正確的運算式。字串的最大長度為128個字元。
Input
輸入的第一列為正整數n,代表接下來有n列待測資料。
Output
檢查每列待測資料,如果正確輸出Yes,否則輸出No。
Sample Input
3

([])
(([()])))
([()[]()])()
Sample Output
Yes
No
Yes

在此附上題目連結
UVA: http://uva.onlinejudge.org/external/6/673.html
LUCKY CAT: http://luckycat.kshs.kh.edu.tw/homework/q673.htm
解題感想:這題難易中,使用堆疊注意括號判斷,應該可以解出
AC CODE:
#include<iostream>
  • #include<cmath>
  • #include<cstdio>
  • #include<vector>
  • #include<cstring>
  • #include<stack>
  • using namespace std;

  • int main()
  • {
  •         char s[200];
  •         int n,ans=0;
  •         cin>>n;
  •         
  •         while(n--)
  •         {        
  •                 stack<char> qq;
  •                 scanf("%s",s);
  •                 for(int i=0;s[i]!='\0';i++)
  •                 {
  •                         if(s[i]=='('||s[i]=='[')
  •                         {
  •                                 qq.push(s[i]);
  •                                        
  •                         }
  •                         if(s[i]==')')
  •                         {
  •                                 if(qq.empty())
  •                                 {
  •                                         ans++;
  •                                         break;
  •                                 }
  •                                 if(qq.top()=='(')
  •                                 {
  •                                         qq.pop();
  •                                        
  •                                 }
  •                         }
  •                         if(s[i]==']')
  •                         {
  •                                 if(qq.empty())
  •                                 {
  •                                         ans++;
  •                                         break;
  •                                 }
  •                                 if(qq.top()=='[')
  •                                 {
  •                                         qq.pop();
  •                                        
  •                                 }
  •                         }
  •                 }
  •                 if(qq.empty()&&ans==0) cout<<"Yes"<<"\n";
  •                 else cout<<"No"<<"\n";
  •                 ans=0;
  •                 while(!qq.empty()) qq.pop();
  •         }
  •         return 0;
  • }
















  • 歡迎光臨 竹園論壇 (http://forum.tfcis.org/) Powered by Discuz! X3.2