-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0020-Valid-parentheses.cs
More file actions
43 lines (38 loc) · 1.17 KB
/
0020-Valid-parentheses.cs
File metadata and controls
43 lines (38 loc) · 1.17 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
using System;
using System.Collections.Generic;
using System.Text;
namespace Solution._0020.Valid_parentheses
{
public class _0020_Valid_parentheses
{
public bool IsValid(string s)
{
if (s.Length % 2 != 0) return false;
Stack<char> stack = new Stack<char>();
// faster
for (int i = 0; i < s.Length; i++)
{
if (s[i] == '(')
stack.Push(')');
else if (s[i] == '[')
stack.Push(']');
else if (s[i] == '{')
stack.Push('}');
else if (stack.Count == 0 || s[i] != stack.Pop())
return false;
}
//foreach (char c in s.ToCharArray())
//{
// if (c == '(')
// stack.Push(')');
// else if (c == '[')
// stack.Push(']');
// else if (c == '{')
// stack.Push('}');
// else if (stack.Count == 0 || c != stack.Pop())
// return false;
//}
return stack.Count == 0;
}
}
}