-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path20.cpp
More file actions
37 lines (37 loc) · 1.04 KB
/
20.cpp
File metadata and controls
37 lines (37 loc) · 1.04 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
// Author: btjanaka (Bryon Tjanaka)
// Problem: (Leetcode) 20
// Title: Valid Parentheses
// Link: https://leetcode.com/problems/valid-parentheses
// Idea: Use a stack to keep track of the current parentheses that you have seen
// while iterating through the array. If the next paren is opening, you push its
// corresponding closing paren on. If it is closing, it should match the top of
// the stack; otherwise, there is an error.
// Difficulty: easy
// Tags: stack
class Solution {
public:
bool isValid(string s) {
stack<char> parens;
for (int i = 0; i < s.size(); ++i) {
switch (s[i]) {
// Push closing parens when seeing open parens
case '(':
parens.push(')');
break;
case '[':
parens.push(']');
break;
case '{':
parens.push('}');
break;
default:
// closing parens
if (parens.empty() || s[i] != parens.top()) {
return false;
}
parens.pop();
}
}
return parens.empty();
}
};