File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed
Algorithms Basics/Chapter 4. Stack and Queue Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change
1
+ // condense and smart one, not a direct thought
2
+ public class Solution {
3
+ public bool IsValid ( string s ) {
4
+ if ( s == null || s . Length == 0 ) return false ;
5
+ if ( s . Length % 2 == 1 ) return false ;
6
+ Stack < char > stack = new Stack < char > ( ) ;
7
+ foreach ( char c in s ) {
8
+ if ( c == '(' ) stack . Push ( ')' ) ;
9
+ else if ( c == '[' ) stack . Push ( ']' ) ;
10
+ else if ( c == '{' ) stack . Push ( '}' ) ;
11
+ else if ( stack . Count == 0 || stack . Pop ( ) != c ) return false ;
12
+ }
13
+ return stack . Count == 0 ;
14
+ }
15
+ }
16
+
17
+ // direct thought solution
18
+ public class Solution {
19
+ public bool IsValid ( string s ) {
20
+ if ( s == null || s . Length == 0 ) return false ;
21
+ if ( s . Length % 2 == 1 ) return false ;
22
+ Stack < char > stack = new Stack < char > ( ) ;
23
+ foreach ( char c in s ) {
24
+ if ( c == '(' || c == '[' || c == '{' ) stack . Push ( c ) ;
25
+ else if ( stack . Count == 0 ) return false ;
26
+ else if ( c == ')' && stack . Peek ( ) == '(' ) stack . Pop ( ) ;
27
+ else if ( c == ']' && stack . Peek ( ) == '[' ) stack . Pop ( ) ;
28
+ else if ( c == '}' && stack . Peek ( ) == '{' ) stack . Pop ( ) ;
29
+ else return false ;
30
+ }
31
+ return stack . Count == 0 ;
32
+ }
33
+ }
You can’t perform that action at this time.
0 commit comments