Skip to content

Commit a2c5d5d

Browse files
committed
Added more test cases for ValidParenthesesTests.cs
Refactored nested if-else to switch-case in ValidParentheses.cs
1 parent bc160b4 commit a2c5d5d

File tree

2 files changed

+36
-20
lines changed

2 files changed

+36
-20
lines changed

Algorithms.Tests/Strings/ValidParenthesesTests.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff 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

Algorithms/Strings/ValidParentheses.cs

Lines changed: 35 additions & 20 deletions
Original file line numberDiff line numberDiff 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

0 commit comments

Comments
 (0)