力扣练习题

发布时间 2023-09-23 21:48:37作者: 新晋软工小白
 1 #include <bits/stdc++.h>
 2 #define MAXSIZE 100
 3 using namespace std;
 4 typedef struct{
 5     char* base;
 6     char* top;
 7     int stactsize;
 8 }sqstack;
 9 void initstack(sqstack &s){
10     s.base=new char[MAXSIZE];
11     if(!s.base){
12         return;
13     }
14     s.top=s.base;
15     s.stactsize=MAXSIZE;
16     return;
17 }
18 void push(sqstack &s,char e){
19     if(s.top-s.base==MAXSIZE){
20         return;
21     }
22     *s.top++=e;
23     return;
24 }
25 void pop(sqstack &s,char &e){
26     if(s.top==s.base){
27         return;
28     }
29     e=*--s.top;
30     return;
31 }
32 bool isValid(char* s){
33     int n=strlen(s);
34     if(n%2!=0){
35         return false;
36     }
37     sqstack S;
38     initstack(S);
39     if(s[0]==')'||s[0]=='}'||s[0]==']'){
40         return false;
41     }
42     for(int i=0;i<n;i++){
43         if(s[i]=='('||s[i]=='{'||s[i]=='['){
44             push(S,s[i]);
45         }
46         if(s[i]==')'||s[i]=='}'||s[i]==']'){
47             char e;
48             pop(S,e);
49             if(e=='(' && s[i]-e!=1){
50             
51                 return false;
52             }
53             if(e!='('&&s[i]-e!=2){
54                     return false;
55             }
56         }
57     }
58     return true;
59 }
60 int main(){
61     char s[MAXSIZE]; 
62     gets(s);
63     int flag=isValid(s);
64     if(flag==1){
65         cout<<"true"<<endl;
66     } 
67     else{
68         cout<<"false"<<endl;
69     }
70 }