-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path20_valid_parentheses.cpp
More file actions
36 lines (36 loc) · 969 Bytes
/
20_valid_parentheses.cpp
File metadata and controls
36 lines (36 loc) · 969 Bytes
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
#include <iostream>
#include <stack>
#include <string>
using namespace std;
// Solution: Use stack to store current opening brackets and pop when closing
// brackets are found
// Time complexity: O(n) where n is the length of the string
class Solution {
public:
bool isValid(string s) {
stack<char> st;
for (char c : s) {
// If c is an opening bracket, push it to the stack
if (c == '(' || c == '[' || c == '{') {
st.push(c);
} else {
// If c is a closing bracket, check if the stack is empty
if (st.empty()) {
return false;
}
// If c is a closing bracket, check if the top of the stack is the same
if (c == ')' && st.top() != '(') {
return false;
}
if (c == ']' && st.top() != '[') {
return false;
}
if (c == '}' && st.top() != '{') {
return false;
}
st.pop();
}
}
return st.empty();
}
};