File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -18,6 +18,7 @@ public static void IsValidParentheses_TrueExpected(string parentheses)
1818 }
1919
2020 [ TestCase ( "([)[}" ) ]
21+ [ TestCase ( "([}}])" ) ]
2122 public static void IsValidParentheses_FalseExpected ( string parentheses )
2223 {
2324 // Arrange
Original file line number Diff line number Diff line change @@ -7,7 +7,7 @@ namespace Algorithms.Strings
77 /// This is a class for checking if the parentheses is valid.
88 /// A valid parentheses should have opening brace and closing brace.
99 /// </summary>
10- public class ValidParentheses
10+ public static class ValidParentheses
1111 {
1212 /// <summary>
1313 /// Function to check if the parentheses is valid.
@@ -22,27 +22,42 @@ public static bool IsValidParentheses(string parentheses)
2222
2323 Stack < char > stack = new Stack < char > ( ) ;
2424
25- foreach ( char c in parentheses . ToCharArray ( ) )
25+ foreach ( char c in parentheses )
2626 {
27- if ( c == '(' || c == '{' || c == '[' )
27+ switch ( c )
2828 {
29- stack . Push ( c ) ;
30- }
31- else if ( c == ')' && stack . Count != 0 && stack . Peek ( ) == '(' )
32- {
33- stack . Pop ( ) ;
34- }
35- else if ( c == '}' && stack . Count != 0 && stack . Peek ( ) == '{' )
36- {
37- stack . Pop ( ) ;
38- }
39- else if ( c == ']' && stack . Count != 0 && stack . Peek ( ) == '[' )
40- {
41- stack . Pop ( ) ;
42- }
43- else
44- {
45- stack . Push ( c ) ;
29+ case '(' :
30+ case '{' :
31+ case '[' :
32+ stack . Push ( c ) ;
33+ break ;
34+
35+ case ')' :
36+ if ( stack . Count == 0 || stack . Pop ( ) != '(' )
37+ {
38+ return false ;
39+ }
40+
41+ break ;
42+
43+ case '}' :
44+ if ( stack . Count == 0 || stack . Pop ( ) != '{' )
45+ {
46+ return false ;
47+ }
48+
49+ break ;
50+
51+ case ']' :
52+ if ( stack . Count == 0 || stack . Pop ( ) != '[' )
53+ {
54+ return false ;
55+ }
56+
57+ break ;
58+
59+ default :
60+ return false ;
4661 }
4762 }
4863
You can’t perform that action at this time.
0 commit comments