File tree Expand file tree Collapse file tree 1 file changed +16
-6
lines changed Expand file tree Collapse file tree 1 file changed +16
-6
lines changed Original file line number Diff line number Diff line change 1
1
class Solution {
2
2
public:
3
+ std::map <char , char > parentheses = {
4
+ { ' {' , ' }' },
5
+ { ' (' , ' )' },
6
+ { ' [' , ' ]' },
7
+ };
8
+
3
9
bool isValid (string s) {
4
10
stack<char > stack;
5
11
6
- if (s[0 ] == ' )' || s[0 ] == ' }' || s[0 ] == ' ]' ){
7
- return false ;
8
- }
9
-
10
12
for (char c : s){
13
+ if (stack.empty () && isCloseParenth (c)){return false ;}
11
14
if (!stack.empty () && isInvalidPair (stack.top (), c)){return false ;}
12
15
13
16
if (c != ' (' && c != ' {' && c != ' [' && !stack.empty () && isPair (stack.top (), c)){
@@ -20,10 +23,17 @@ class Solution {
20
23
}
21
24
22
25
bool isPair (char l, char r){
23
- return (l == ' (' && r == ' )' || l == ' {' && r == ' }' || l == ' [' && r == ' ]' );
26
+ return parentheses[l] == r;
27
+ }
28
+
29
+ bool isCloseParenth (char c){
30
+ for (auto p: parentheses){
31
+ if (p.second == c){return true ;}
32
+ }
33
+ return false ;
24
34
}
25
35
26
36
bool isInvalidPair (char l, char r){
27
- return (l == ' ( ' && (r == ' } ' || r == ' ] ' )) || (l == ' { ' && (r == ' ) ' || r == ' ] ' )) || (l == ' [ ' && (r == ' } ' || r == ' ) ' )) ;
37
+ return isCloseParenth (r) && parentheses[l] != r ;
28
38
}
29
39
};
You can’t perform that action at this time.
0 commit comments