2 条题解

  • 0
    @ 2024-8-2 20:15:54
    #include<cstdio>
    #include<iostream>
    #include<string>
    #include<cstring>
    using namespace std;
    string s;
    char sta[6000];
    int main()
    {
    	cin>>s;
    	int top=0;
    	for (int i=0;i<s.size();i++)
    	{
    		sta[++top]=s[i];
    		if (s[i]==')')
    		{
    			if (sta[top-1]=='(')
    				top-=2;			
    		}
    		else
    		{
    			if (s[i]==']')
    				if (sta[top-1]=='[')
    				top-=2;
    		}
    		
    	}
    	if (top!=0)
    		printf("Wrong");
    	else
    		printf("OK");
    	return 0;
    }
    
    • 0
      @ 2023-10-2 23:25:58

      栈,初尝试

      #include<iostream>
      #include<string>
      using namespace std;
      int main(){
      	string s;
      	cin>>s;
      	int k=0;//栈顶指针
      	int t[256];
      	char a;
      	for(int i=0;i<s.size();i++){//遍历字符串,匹配括弧
      		if(s[i]=='('||s[i]=='['){
      			a=s[i];//更新待匹配左括弧
      			t[k++]=i;//入栈
      		}
      		else if((s[i]==')'&&a=='(')||(s[i]==']'&&a=='[')){//判断是否与待匹配左括弧对应
      			k--;//弹出栈顶元素;
      			if(k>0)//不为空栈,则更新待匹配左括弧
      			a=s[t[k-1]];
      			else a=' ';//空栈,则清空待匹配标记
      		}
      		else{//无左括弧入栈,且右括弧不匹配,则匹配失败,退出程序
      			cout<<"Wrong";
      			return 0;
      		}
      	}
      	if(k==0) cout<<"OK";//空栈,匹配成功
      	else cout<<"Wrong";//不为空栈
      }
      
      • 1

      信息

      ID
      703
      时间
      1000ms
      内存
      256MiB
      难度
      1
      标签
      递交数
      140
      已通过
      27
      上传者