-
Notifications
You must be signed in to change notification settings - Fork 120
/
Copy path020-ValidParentheses.cs
37 lines (33 loc) · 1.11 KB
/
020-ValidParentheses.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
//-----------------------------------------------------------------------------
// Runtime: 68ms
// Memory Usage: 21.9 MB
// Link: https://leetcode.com/submissions/detail/358336005/
//-----------------------------------------------------------------------------
using System.Collections.Generic;
namespace LeetCode
{
public class _020_ValidParentheses
{
public bool IsValid(string s)
{
var stack = new Stack<char>();
foreach (var ch in s)
{
if (ch == '(' || ch == '[' || ch == '{')
stack.Push(ch);
else if (ch == ')' || ch == ']' || ch == '}')
{
if (stack.Count <= 0) return false;
var lastCh = stack.Peek();
if ((ch == ')' && lastCh == '(') ||
(ch == ']' && lastCh == '[') ||
(ch == '}' && lastCh == '{'))
stack.Pop();
else
return false;
}
}
return stack.Count == 0;
}
}
}