-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path191025-1.cpp
50 lines (48 loc) · 1.04 KB
/
191025-1.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
// https://leetcode-cn.com/problems/valid-parentheses/
#include <cstdio>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
bool isValid(string s) {
vector<char> stack(s.size());
int i = -1;
for (const char* p = s.c_str(); *p; ++p) {
if (*p == ')') {
if (i >= 0 && stack[i] == '(') {
--i;
} else {
return false;
}
} else if (*p == ']') {
if (i >= 0 && stack[i] == '[') {
--i;
} else {
return false;
}
} else if (*p == '}') {
if (i >= 0 && stack[i] == '{') {
--i;
} else {
return false;
}
} else {
stack[++i] = *p;
}
}
return (i == -1);
}
};
int main()
{
Solution s;
printf("%d\n", s.isValid("()")); // answer: true
printf("%d\n", s.isValid("()[]{}")); // answer: true
printf("%d\n", s.isValid("(]")); // answer: false
printf("%d\n", s.isValid("([)]")); // answer: false
printf("%d\n", s.isValid("{[]}")); // answer: true
printf("%d\n", s.isValid("[")); // answer: false
printf("%d\n", s.isValid("")); // answer: true
return 0;
}