-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path20.valid-parentheses.cs
43 lines (38 loc) · 1.14 KB
/
20.valid-parentheses.cs
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
/*
* @lc app=leetcode id=20 lang=csharp
*
* [20] Valid Parentheses
*/
// @lc code=start
public class Solution {
public bool IsValid(string s) {
// stack for open parantheses
var paranthesesStack = new Stack<char>();
foreach(char c in s){
// push open parantheses to stack
if(c == '(' || c == '[' || c == '{'){
paranthesesStack.Push(c);
} else {
// don't pop from empty stack
if(paranthesesStack.Count == 0){
return false;
}
// pop from stack and compare if counterpart
// otherwise the parantheses are invalid
char top = paranthesesStack.Pop();
if(c == ')' && top != '('){
return false;
}
if(c == ']' && top != '['){
return false;
}
if(c == '}' && top != '{'){
return false;
}
}
}
// return true if stack is empty
return paranthesesStack.Count == 0;
}
}
// @lc code=end