-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path020-valid-parentheses.cpp
More file actions
47 lines (40 loc) · 1.2 KB
/
Copy path020-valid-parentheses.cpp
File metadata and controls
47 lines (40 loc) · 1.2 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
// 20. Valid Parentheses
//
// Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
// The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
//
// Tags: Stack, String
//
// https://leetcode.com/problems/valid-parentheses/
#include <iostream>
#include <gtest/gtest.h>
#include <stack>
using namespace std;
class Solution {
public:
bool isValid(string s) {
stack<char> st;
for(auto c: s){
if(st.empty()){
st.push(c);
}else if( (c == ')' && st.top() == '(') || (c == '}' && st.top() == '{') || (c == ']' && st.top() == '[')){
st.pop();
}else{
st.push(c);
}
}
return st.empty();
}
};
TEST(leetcode_020_valid_parentheses, Basic)
{
Solution *solution = new Solution();
EXPECT_TRUE(solution->isValid("()"));
EXPECT_TRUE(solution->isValid("()[]{}"));
EXPECT_FALSE(solution->isValid("(]"));
EXPECT_FALSE(solution->isValid("([)]"));
}
int main(int argc, char *argv[]) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}