-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path020.ValidParentheses.cpp
More file actions
81 lines (74 loc) · 2.14 KB
/
020.ValidParentheses.cpp
File metadata and controls
81 lines (74 loc) · 2.14 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
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
/*Question:
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
Tags: stack, string
Similar Problems:
22, 32, 302
*/
/*思路:
如果是( [ {则进栈,否则与栈顶元素比较
方法二借助了string直接实现
*/
//Code:
//Code 1:
class Solution {
public:
bool isValid(string s) {
if(s.size() <= 1) return false;
std::vector<char> check;
for(auto item: s)
{
switch(item)
{
case '(':
check.push_back(item);
break;
case '[':
check.push_back(item);
break;
case '{':
check.push_back(item);
break;
case ')':
if(check.empty() || check.back() != '(')
return false;
check.pop_back();
break;
case ']':
if(check.empty() || check.back() != '[')
return false;
check.pop_back();
break;
case '}':
if(check.empty() || check.back() != '{')
return false;
check.pop_back();
break;
default:
break;
}
}
if(check.empty()) return true;
return false;
}
};
//Code 2:
class Solution {
public:
bool isValid(string s) {
if(s.size() <= 1) return false;
std::string check;
for(auto item: s)
{
if(item == ')' && check.back() == '(')
check.pop_back();
else if(item == ']' && check.back() == '[')
check.pop_back();
else if(item == '}' && check.back() == '{')
check.pop_back();
else
check.push_back(item);
}
return check.empty();
}
};