使用堆栈算法进行括号/括号匹配

Parenthesis/Brackets Matching using Stack algorithm(使用堆栈算法进行括号/括号匹配)

本文介绍了使用堆栈算法进行括号/括号匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果括号/括号在以下匹配:

For example if the parenthesis/brackets is matching in the following:

({})
(()){}()
()

以此类推,但如果括号/括号不匹配,则应返回 false,例如:

and so on but if the parenthesis/brackets is not matching it should return false, eg:

{}
({}(
){})
(()

等等.你能检查一下这个代码吗?提前致谢.

and so on. Can you please check this code? Thanks in advance.

public static boolean isParenthesisMatch(String str) {
    Stack<Character> stack = new Stack<Character>();

    char c;
    for(int i=0; i < str.length(); i++) {
        c = str.charAt(i);

        if(c == '{')
            return false;

        if(c == '(')
            stack.push(c);

        if(c == '{') {
            stack.push(c);
            if(c == '}')
                if(stack.empty())
                    return false;
                else if(stack.peek() == '{')
                    stack.pop();
        }
        else if(c == ')')
            if(stack.empty())
                return false;
            else if(stack.peek() == '(')
                    stack.pop();
                else
                    return false;
        }
        return stack.empty();
}

public static void main(String[] args) {        
    String str = "({})";
    System.out.println(Weekly12.parenthesisOtherMatching(str)); 
}

推荐答案

您的代码在处理{"和}"字符时有些混乱.它应该与您处理 '(' 和 ')' 的方式完全平行.

Your code has some confusion in its handling of the '{' and '}' characters. It should be entirely parallel to how you handle '(' and ')'.

这段代码稍加修改,似乎可以正常工作:

This code, modified slightly from yours, seems to work properly:

public static boolean isParenthesisMatch(String str) {
    if (str.charAt(0) == '{')
        return false;

    Stack<Character> stack = new Stack<Character>();

    char c;
    for(int i=0; i < str.length(); i++) {
        c = str.charAt(i);

        if(c == '(')
            stack.push(c);
        else if(c == '{')
            stack.push(c);
        else if(c == ')')
            if(stack.empty())
                return false;
            else if(stack.peek() == '(')
                stack.pop();
            else
                return false;
        else if(c == '}')
            if(stack.empty())
                return false;
            else if(stack.peek() == '{')
                stack.pop();
            else
                return false;
    }
    return stack.empty();
}

这篇关于使用堆栈算法进行括号/括号匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:使用堆栈算法进行括号/括号匹配

基础教程推荐