-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValid_Parentheses.cpp
More file actions
56 lines (47 loc) · 1.18 KB
/
Valid_Parentheses.cpp
File metadata and controls
56 lines (47 loc) · 1.18 KB
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
// 下面有更快速寫法 //
#include<iostream>
#include<string>
#include<stack>
using namespace std;
int main(){
stack <int> stk;
string s = ")";
char check ;
for(int i=0; i<s.length();i++){
if (s[i] == '(' || s[i] == '[' || s[i] == '{') {
stk.push(s[i]);
}else{
if(stk.empty()){stk.push(s[i]);}
check = stk.top();
if ((check == '(' && s[i] == ')') || (check == '[' && s[i] == ']') || (check == '{' && s[i] == '}')) {
stk.pop();
continue;
}
else{
break;
}
}
}
if(stk.empty()){
cout << "true";
}else{
cout << "false";
}
return 0;
}
/// 更快速的寫法 ///
// stack <char> stk;
// for(char check: s){
// if (check == '[' || check == '{' || check == '('){
// stk.push(check);
// }else{
// if(stk.empty() ||
// (check ==')' && stk.top() != '(') ||
// (check ==']' && stk.top() != '[') ||
// (check =='}' && stk.top() != '{') ){
// return false;
// }
// stk.pop();
// }
// }
// return stk.empty();