-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path20_valid_parentheses.cpp
More file actions
109 lines (82 loc) · 2.12 KB
/
Copy path20_valid_parentheses.cpp
File metadata and controls
109 lines (82 loc) · 2.12 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
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
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool isValid(string s) {
stack<char> openBrackets;
for (char bracket : s) {
if (isOpenBracket(bracket)) {
openBrackets.push(bracket);
continue;
}
if (openBrackets.empty()) {
return false;
}
char lastOpen = openBrackets.top();
openBrackets.pop();
if (!isMatching(lastOpen, bracket)) {
return false;
}
}
return openBrackets.empty();
}
private:
bool isOpenBracket(char c) {
return c == '(' || c == '{' || c == '[';
}
bool isMatching(char open, char close) {
bool first = open == '(' && close == ')';
bool second = open == '{' && close == '}';
bool third = open == '[' && close == ']';
return first || second || third;
}
};
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
string str = "([{}])";
Solution solve;
bool result = solve.isValid(str);
cout << (result ? "true\n" : "false\n");
return 0;
}
/*
------------------
Problem Statement:
------------------
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
1. Open brackets must be closed by the same type of brackets.
2. Open brackets must be closed in the correct order.
3. Every close bracket has a corresponding open bracket of the same type.
----------
Example 1:
----------
Input: s = "()"
Output: true
----------
Example 2:
----------
Input: s = "()[]{}"
Output: true
----------
Example 3:
----------
Input: s = "(]"
Output: false
----------
Example 4:
----------
Input: s = "([])"
Output: true
----------
Example 5:
----------
Input: s = "([)]"
Output: false
------------
Constraints:
------------
1 <= s.length <= 10^4
s consists of parentheses only '()[]{}'.
*/