File tree Expand file tree Collapse file tree 2 files changed +36
-20
lines changed Expand file tree Collapse file tree 2 files changed +36
-20
lines changed Original file line number Diff line number Diff line change @@ -18,6 +18,7 @@ public static void IsValidParentheses_TrueExpected(string parentheses)
18
18
}
19
19
20
20
[ TestCase ( "([)[}" ) ]
21
+ [ TestCase ( "([}}])" ) ]
21
22
public static void IsValidParentheses_FalseExpected ( string parentheses )
22
23
{
23
24
// Arrange
Original file line number Diff line number Diff line change @@ -7,7 +7,7 @@ namespace Algorithms.Strings
7
7
/// This is a class for checking if the parentheses is valid.
8
8
/// A valid parentheses should have opening brace and closing brace.
9
9
/// </summary>
10
- public class ValidParentheses
10
+ public static class ValidParentheses
11
11
{
12
12
/// <summary>
13
13
/// Function to check if the parentheses is valid.
@@ -22,27 +22,42 @@ public static bool IsValidParentheses(string parentheses)
22
22
23
23
Stack < char > stack = new Stack < char > ( ) ;
24
24
25
- foreach ( char c in parentheses . ToCharArray ( ) )
25
+ foreach ( char c in parentheses )
26
26
{
27
- if ( c == '(' || c == '{' || c == '[' )
27
+ switch ( c )
28
28
{
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 ;
46
61
}
47
62
}
48
63
You can’t perform that action at this time.
0 commit comments