-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValid Parantheses.cs
More file actions
69 lines (58 loc) · 1.67 KB
/
Copy pathValid Parantheses.cs
File metadata and controls
69 lines (58 loc) · 1.67 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
68
69
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace LeetCodeTests
{
public class Parantheses
{
static void Main(string[] args)
{
Console.WriteLine(IsValid("([]{})"));
Console.ReadLine();
}
public static bool IsValid(string s)
{
/*Create a Stack to store opening parantheses*/
Stack myStack = new Stack();
/*Loop every char in the string*/
foreach (char c in s)
{
/*If it is a 'Open bracket' - add to the stack*/
if (c == '(' || c == '{' || c == '[')
{
myStack.Push(c);
}
/*If there are no 'open brackets' - return false*/
if (myStack.Count == 0)
{
return false;
}
else if(c == ')' || c == '}' || c == ']')
{
/*Search for the corresponding bracket at the top of the stack, if they dont match it means they are out of order - return false
* else (Matched open and close brackets) remove from the stack ()*/
if (c == ')' && myStack.Peek().ToString() != "(") {
return false;
}
else if (c == '}' && myStack.Peek().ToString() != "{") {
return false;
}
else if (c == ']' && myStack.Peek().ToString() != "[") {
return false;
}
else myStack.Pop();
}
}
/*If the stack has CHRS, it means that the brackets are out of order - return false*/
if (myStack.Count != 0)
{
return false;
}
/*if we could remove all of them - it means they are in order (open and close) - return true*/
return true;
}
}
}