-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathValidParentheses.cs
More file actions
67 lines (56 loc) · 1.77 KB
/
Copy pathValidParentheses.cs
File metadata and controls
67 lines (56 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
using System;
using System.Collections.Generic;
namespace Algorithms.Strings
{
/// <summary>
/// This is a class for checking if the parentheses is valid.
/// A valid parentheses should have opening brace and closing brace.
/// </summary>
public static class ValidParentheses
{
/// <summary>
/// Function to check if the parentheses is valid.
/// </summary>
/// <param name="parentheses">String to be checked.</param>
public static bool IsValidParentheses(string parentheses)
{
if (parentheses.Length % 2 != 0)
{
return false;
}
Stack<char> stack = new Stack<char>();
foreach(char c in parentheses)
{
switch (c)
{
case '(':
case '{':
case '[':
stack.Push(c);
break;
case ')':
if (stack.Count == 0 || stack.Pop() != '(')
{
return false;
}
break;
case '}':
if (stack.Count == 0 || stack.Pop() != '{')
{
return false;
}
break;
case ']':
if (stack.Count == 0 || stack.Pop() != '[')
{
return false;
}
break;
default:
return false;
}
}
return stack.Count == 0;
}
}
}