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。

转载于:https://www.cnblogs.com/etcow/archive/2012/10/23/2734816.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值