-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path20ValidParentheses.cs
69 lines (61 loc) · 1.83 KB
/
20ValidParentheses.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
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;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _20ValidParentheses
{
class Program
{
static void Main(string[] args)
{
}
/*
* cod reference:
* http://blog.csdn.net/fightforyourdream/article/details/13011825
*
* julia's comment:
* 1. pass online judge
* 65 / 65 test cases passed.
Status: Accepted
Runtime: 124 ms
*/
public static bool isValid(String s)
{
Stack stack = new Stack();
for (int i = 0; i < s.Length; i++)
{
char current = s[i];
// 如果遇到前括号就压入栈
if (current == '(' || current == '[' || current == '{')
{
stack.Push(current);
}
else if (current == ')' || current == ']' || current == '}')
{ // 遇到后括号就出栈
if (stack.Count == 0)
{
// 说明后括号太多了
return false;
}
char previous = (char)stack.Pop();
if (previous == '(' && current == ')')
{
continue;
}
else if (previous == '[' && current == ']')
{
continue;
}
else if (previous == '{' && current == '}')
{
continue;
}
return false;
}
}
return stack.Count == 0;
}
}
}