-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0020-Valid_Parentheses.cpp
More file actions
91 lines (82 loc) · 2.12 KB
/
0020-Valid_Parentheses.cpp
File metadata and controls
91 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
/*******************************************************************************
* 0020-Valid_Parentheses.cpp
* Billy.Ljm
* 10 Apr 2023
*
* =======
* Problem
* =======
* https://leetcode.com/problems/valid-parentheses/
* Given a string s containing just the characters '(', ')', '{', '}', '[' and
* ']', determine if the input string is valid.
*
* An input string is valid if:
* - Open brackets must be closed by the same type of brackets.
* - Open brackets must be closed in the correct order.
* - Every close bracket has a corresponding open bracket of the same type.
*
* ===========
* My Approach
* ===========
* We can use a LIFO stack to keep track of the opening brackets. Then, if we
* encounter a closing bracket, we just check it against the top of the stack.
*
* This has a time complexity of O(n) and space complexity of O(n), where n is
* the length of the string.
******************************************************************************/
#include <iostream>
#include <string>
#include <stack>
class Solution {
public:
bool isValid(std::string s) {
std::stack<char> stack;
for (char c : s) {
// if open bracket, push to stack
if (c == '(' || c == '[' || c == '{') {
stack.push(c);
}
// if close bracket, check w/ top of stack
else if (c == ')') {
if (stack.empty() || stack.top() != '(') {
return false;
}
stack.pop();
}
else if (c == ']') {
if (stack.empty() || stack.top() != '[') {
return false;
}
stack.pop();
}
else if (c == '}') {
if (stack.empty() || stack.top() != '{') {
return false;
}
stack.pop();
}
}
// check if any open brackets remaining
return stack.empty();
}
};
/**
* Test cases
*/
int main(void) {
Solution sol;
std::string s;
// test case 1
s = "()";
std::cout << std::boolalpha << "isValid(" << s << ") = " << sol.isValid(s)
<< std::endl;
// test case 2
s = "()[]{}";
std::cout << std::boolalpha << "isValid(" << s << ") = " << sol.isValid(s)
<< std::endl;
// test case 3
s = "(]";
std::cout << std::boolalpha << "isValid(" << s << ") = " << sol.isValid(s)
<< std::endl;
return 0;
}