forked from LeetCode-in-Cpp/LeetCode-in-Cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.cpp
28 lines (26 loc) · 888 Bytes
/
Solution.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
// #Easy #Top_100_Liked_Questions #Top_Interview_Questions #String #Stack
// #Data_Structure_I_Day_9_Stack_Queue #Udemy_Strings #Big_O_Time_O(n)_Space_O(n)
// #2024_05_23_Time_0_ms_(100.00%)_Space_7.6_MB_(59.50%)
#include <stack>
#include <string>
using namespace std;
class Solution {
public:
bool isValid(string s) {
stack<char> stack;
for (char c : s) {
if (c == '(' || c == '[' || c == '{') {
stack.push(c);
} else if (c == ')' && !stack.empty() && stack.top() == '(') {
stack.pop();
} else if (c == '}' && !stack.empty() && stack.top() == '{') {
stack.pop();
} else if (c == ']' && !stack.empty() && stack.top() == '[') {
stack.pop();
} else {
return false;
}
}
return stack.empty();
}
};