LeetCode Online Judge 题目C# 练习 - Valid Parentheses

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

 1         public static bool ValidParentheses(string s)
 2         {
 3             Stack<char> stack = new Stack<char>();
 4 
 5             for (int i = 0; i < s.Length; i++)
 6             {
 7                 if (s[i] == '(' || s[i] == '[' || s[i] == '{')
 8                     stack.Push(s[i]);
 9                 else
10                 {
11                     // begin with ')', ']' or '}'?
12                     if (stack.Count == 0)
13                         return false;
14                     
15                     if (s[i] == ')')
16                     {
17                         if (stack.Peek() == '(')
18                         {
19                             stack.Pop();
20                         }
21                         else
22                             return false;
23                     }
24                     else if (s[i] == ']')
25                     {
26                         if (stack.Peek() == '[')
27                         {
28                             stack.Pop();
29                         }
30                         else
31                             return false;
32                     }
33                     else if (s[i] == '}')
34                     {
35                         if (stack.Peek() == '{')
36                         {
37                             stack.Pop();
38                         }
39                         else
40                             return false;
41                     }
42                 }
43             }
44 
45             return stack.Count == 0;
46         }

代码分析:

  比较简单,一个Stack, 左括号(大,中,小)往里push, 右括号,pop出来,不match return false, 

  最后要看stack里是否空,不空则左括号多了,return false。

posted @ 2012-10-23 03:39  ETCOW  阅读(439)  评论(0编辑  收藏  举报