-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathValid Parentheses.cpp
executable file
·118 lines (107 loc) · 1.66 KB
/
Valid Parentheses.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
#include"head.h"
class Stack{
public:
Stack(int length){
arr=new char[2*length];
top=-1;
capacity=2*length;
}
void push(char e){
if(top==capacity){
exit(1);
}
arr[++top]=e;
}
void pop(){
if(top==-1)
return;
--top;
}
char getTop(){
if(top!=-1)
return arr[top];
else
return '#';
}
bool isEmpty(){
return top==-1;
}
char *arr;
int top;
int capacity;
};
bool isMatched(char c1,char c2){
switch(c1){
case '(':
if(c2==')')
return true;
else
return false;
break;
case '[':
if(c2==']')
return true;
else
return false;
break;
case '{':
if(c2=='}')
return true;
else
return false;
break;
default:
return false;
}
}
bool isValid(string s){
if(""==s)
return true;
int length=s.length();
Stack stk(length);
for(int i=0;i<length;i++){
if(s[i]=='{' || s[i]=='[' || s[i]=='(')
stk.push(s[i]);
else if('}'==s[i] || ']'==s[i] || ')'==s[i]){
if(stk.isEmpty())
return false;
else if(!isMatched(stk.getTop(),s[i]))
return false;
else
stk.pop();
}
else
return false;
}
if(stk.isEmpty())
return true;
else
return false;
}
bool isValid1(string s){
stack<char> buf;
for(int i=0;i<s.length();i++){
char c=s[i];
if('{'==c || '['==c || '('==c)
buf.push(c);
else{
if(buf.size()==0)
return false;
char top=buf.top();
if(c=='}'){
if(top!='{')
return false;
}
else if(c==']'){
if(top!='[')
return false;
}
else if(c==')'){
if(top!='(')
return false;
}
buf.pop();
}
}
return buf.size()==0;
}