rwkj 1378 stack(括弧匹配)

來源:互聯網
上載者:User

標籤:java   os   io   資料   for   ar   cti   時間   

C++:泛型程式設計stack(括弧匹配)
時間限制(普通/Java):1000MS/3000MS 運行記憶體限制:65536KByte
總提交:72 測試通過:39

描述


假設運算式中包含一種括弧:圓括弧,其嵌套順序隨意,即(()())或(())等為正確的格式,)(或((())或())均為不正確的格式。檢驗括弧是否匹配可以用堆棧來實現當遇到 ( 時進棧,遇到 ) 時出棧進行匹配檢驗,如果出現不匹配的情況立即結束,否則繼續取下一個字元。如果沒有遇到不匹配的情況,最後判斷棧是否為空白,棧為空白,括弧匹配,否則不匹配。


輸入


包括多組資料。每組1行,為包含括弧的運算式。


輸出


如果是正確的格式,輸出“Yes”,否則輸出“No”


範例輸入

(()())
(())
(()
())
(
)

範例輸出

Yes
Yes
No
No
No
No

題目來源

 

 


#include<algorithm>
#include<bitset>
#include<cmath>
#include<ctime>
#include<cstdio>
#include<cassert>
#include<cstring>
#include<cstdlib>
#include<functional>
#include<iostream>
#include<list>
#include<map>
#include<numeric>
#include<set>
#include<stack>
#include<string>
#include<sstream>
#include<queue>
#include<vector>
using namespace std;
int main()
{
string s;
while(cin>>s)
{
while(s.find("()")!=string::npos)
s.erase(s.find("()"),2);
if(s.size())
cout<<"No"<<endl;
else cout<<"Yes"<<endl;
}
return 0;
}

 

 

****************************

 


//1378

#include<iostream>
using namespace std;
#include<cstring>
#include<stack>
int main()
{
char a[100];
int i,k;
stack<char>s;
while(cin>>a)
{
k=1;
for(i=0;i<strlen(a);i++)
{
if(k==0) break;
if(a[i]==‘(‘) s.push(a[i]);
else
{ if(s.empty()) k=0;
else if(s.top()!=‘(‘) k=0;
else s.pop();
}
}
if(k==1&&s.empty()) cout<<"Yes"<<endl;
else cout<<"No"<<endl;
while(!s.empty()) s.pop();
}
return 0;
}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.