您的位置:首页 > 编程语言 > Go语言

HackRank Stacks: Balanced Brackets;/Leetcode valid-parentheses; 括号匹配

2016-09-29 23:05 465 查看
原题链接:https://www.hackerrank.com/contests/master/challenges/ctci-balanced-brackets?h_r=internal-search

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.

Sample Input

3
{[()]}
{[(])}
{{[[(())]]}}


Sample Output

YES
NO
YES


更多例子:

"()" yes;

")(" no;

"(abcd(e)" no;

"(a)(b)" yes。

([)] No(特别要注意这个测试用例)

Explanation

The string 
{[()]}
 meets
both criteria for being a balanced string, so we print 
YES
 on
a new line.

The string 
{[(])}
 is
not balanced, because the brackets enclosed by the matched pairs 
[(]
 and 
(])
 are
not balanced. Thus, we print 
NO
 on
a new line.

The string 
{{[[(())]]}}
 meets
both criteria for being a balanced string, so we print 
YES
 on
a new line.
题目出自HackRank

思路:
1 使用Stack<char>处理;
2 程序开始和结束时,stack都应该是空的;
3 程序中途应该注意匹配

C#代码:
/// <summary>
/// 输入小括号、中括号、大括号,判断是否匹配;
/// 举例:
/// {[()]} YES
///{[(])}  NO
///{{[[(())]]}} YES
///([)] No
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static bool IsBalancedBrackets(string str)
{
 if (string.IsNullOrEmpty(str))
                return false;

            Stack<char> stack = new Stack<char>();
            char[] charArr = str.ToCharArray();

            for (int i = 0; i < charArr.Length; i++)
            {
                if (charArr[i].Equals('('))
                    stack.Push(charArr[i]);
                else if (charArr[i].Equals('['))
                    stack.Push(charArr[i]);
                else if (charArr[i].Equals('{'))
                    stack.Push(charArr[i]);

                else if (charArr[i].Equals(')'))
                {
                    if (stack.Count == 0 || stack.Pop() != '(')
                        return false;
                }            
                else if (charArr[i].Equals(']'))
                {
                    if (stack.Count == 0 || stack.Pop() != '[')
                        return false;
                }             
                else if(charArr[i].Equals('}'))
                {
                    if (stack.Count == 0 || stack.Pop() != '{')
                        return false;
                }
            }

            if (stack.Count == 0 && stack.Count == 0 && stack.Count == 0)
                return true;
            else
                return false;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息