Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 5bec4b6

Browse files
authored
20 Valid Parentheses
1 parent 1ceb60f commit 5bec4b6

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

csharp/20-Valid-Parentheses.cs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
using System;
2+
namespace AlgoPractice
3+
{
4+
public class Solution
5+
{
6+
public bool IsValid(string s)
7+
{
8+
var map = new Dictionary<char, char>
9+
{
10+
[')'] = '(',
11+
['}'] = '{',
12+
[']'] = '['
13+
};
14+
15+
var stack = new Stack<char>();
16+
foreach(char c in s)
17+
{
18+
if (map.ContainsKey(c))
19+
{
20+
var matchingPar = stack.Count == 0 ? '#' : stack.Pop();
21+
if(map[c] != matchingPar)
22+
{
23+
return false;
24+
}
25+
}
26+
else
27+
{
28+
stack.Push(c);
29+
}
30+
}
31+
return stack.Count == 0;
32+
}
33+
}
34+
}
35+

0 commit comments

Comments
 (0)