文章

141

粉丝

68

获赞

400

访问

31.2k

头像
判断字符串是否有效 题解:经典栈问题
P5230
发布于2025年3月12日 11:47
阅读数 11

#include <bits/stdc++.h>
using namespace std;

int main() {
	string s;
	while(cin>>s){
	    stack<char>st;
	    bool flag=true;
	    for(auto x:s){
	        if(x=='('||x=='['){
	            st.push(x);
	        }else{
	            if(st.empty()){
	                flag=false;
	                break;
	            }else{
	                char t=st.top();
	                if((t=='('&&x==')')||(t=='['&&x==']')){
	                    st.pop();
	                }else{
	                    flag=false;
	                    break;
	                }
	            }
	        }
	    }
	    if(!st.empty())flag=false;
	    if(flag)cout<<1<<endl;
	    else cout<<0<<endl;
	}

}

只需要左输入,右判断即可完成任务。

登录查看完整内容


登录后发布评论

暂无评论,来抢沙发