--- title: 2A 括弧配對(Easy) tags: solution --- # A. 括弧配對(Easy) ## 常規解 由於一組`(`和`)`遇到就會相互抵消, 同理`((`遇`))`也會相互抵消 (裡面那層會先被抵銷,再來才到外面那層)。 稍微把問題簡化一點,可以看成正負相抵消的累積問題。 設遇 `(` 則`+1`、遇 `)` 則`-1`, 一但累積值<0,那麼代表`)`的數量比`(`多,所以必然為錯, 如果結束時累積值>0,那麼代表還有`(`還沒有被消掉。 ```cpp= # include <iostream> using namespace std; int main(){ int T; string s; int x,l; int left; cin>>T; getline(cin,s); while(T--){ getline(cin,s); left = 0; l = s.size(); for(x = 0 ; x<l && left>=0; x++){ if(s[x] == '(') left++; else if(s[x] == ')') left--; } cout<<(left == 0 ? "Yes\n" : "No\n"); } } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up