单调栈-括号匹配

括号匹配是一个非常典型的单调栈问题

利用括号本身左右对应,且左括号的下一个有括号必定匹配的性质

栈本身的出栈,压栈就能完美解决.

代码如下

package org.example;

class CharStack {
    private final int STACK_MAX_SIZE = 100;
    private int top;
    char[] data = new char[STACK_MAX_SIZE];

    public CharStack() {
        this.top = -1;
    }

    public void outputStack() {
        for (int i = 0; i <= this.top; i++) {
            System.out.printf("%c ", this.data[i]);
        }// Of for i
        System.out.println();
    }

    public void push(char paraValue) {
        // Step 1. Space check.
        if (this.top >= this.STACK_MAX_SIZE) {
            System.out.println("Cannot push element: stack full.\r");
            return;
        }//Of if

        // Step 2. Update the top.
        this.top++;

        // Step 3. Push element.
        this.data[this.top] = paraValue;
    }

    public char pop() {
        // Step 1. Space check.
        if (this.top < 0) {
            System.out.println("Cannot pop element: stack empty.\r");
            return '\0';
        }//Of if

        // Step 2. Update the top.
        this.top--;

        // Step 3. Push element.
        return this.data[this.top + 1];
    }
}

public class Dome1 {
    static void pushPopTest() {
        System.out.print("---- pushPopTest begins. ----\r\n");
        char ch;

        // Initialize.
        CharStack tempStack = new CharStack();
        System.out.print("After initialization, the stack is: ");
        tempStack.outputStack();

        // Pop.
        for (ch = 'a'; ch < 'm'; ch++) {
            System.out.printf("Pushing %c.\r\n", ch);
            tempStack.push(ch);
            tempStack.outputStack();
        }//Of for i

        // Pop.
        for (int i = 0; i < 3; i++) {
            ch = tempStack.pop();
            System.out.printf("Pop %c.\r\n", ch);
            tempStack.outputStack();
        }//Of for i

        System.out.print("---- pushPopTest ends. ----\r\n");
    }

    static void bracketMatchingTest() {
        String tempExpression = "[2 + (1 - 3)] * 4";
        boolean tempMatch = bracketMatching(tempExpression, tempExpression.length());
        System.out.printf("Is the expression '" + tempExpression + "' bracket matching? " + tempMatch + "\r\n");

        tempExpression = "( )  )";
        tempMatch = bracketMatching(tempExpression, tempExpression.length());
        System.out.printf("Is the expression '" + tempExpression + "' bracket matching? " + tempMatch + "\r\n");

        tempExpression = "()()(())";
        tempMatch = bracketMatching(tempExpression, tempExpression.length());
        System.out.printf("Is the expression '" + tempExpression + "' bracket matching? " + tempMatch + "\r\n");

        tempExpression = "({}[])";
        tempMatch = bracketMatching(tempExpression, tempExpression.length());
        System.out.printf("Is the expression '" + tempExpression + "' bracket matching? " + tempMatch + "\r\n");

        tempExpression = ")(";
        tempMatch = bracketMatching(tempExpression, tempExpression.length());
        System.out.printf("Is the expression '" + tempExpression + "' bracket matching? " + tempMatch + "\r\n");
    }

    public static boolean bracketMatching(String paraString, int paraLength) {
        // Step 1. Initialize the stack through pushing a '#' at the bottom.
        CharStack tempStack = new CharStack();
        tempStack.push('#');
        char tempChar, tempPopedChar;

        // Step 2. Process the string.
        for (int i = 0; i < paraLength; i++) {
            tempChar = paraString.charAt(i);

            switch (tempChar) {
                case '(', '[', '{' -> tempStack.push(tempChar);
                case ')' -> {
                    tempPopedChar = tempStack.pop();
                    if (tempPopedChar != '(') {
                        return false;
                    } // Of if
                }
                case ']' -> {
                    tempPopedChar = tempStack.pop();
                    if (tempPopedChar != '[') {
                        return false;
                    } // Of if
                }
                case '}' -> {
                    tempPopedChar = tempStack.pop();
                    if (tempPopedChar != '{') {
                        return false;
                    } // Of if
                }
                default -> {
                }
                // Do nothing.
            }// Of switch
        } // Of for i

        tempPopedChar = tempStack.pop();
        // Of if
        return tempPopedChar == '#';
    }

    public static void main(String[] args) {
        //pushPopTest();
        bracketMatchingTest();
    }
}

运行结果如下:

 其中bracketMatching方法即运行的业务层代码

    public static boolean bracketMatching(String paraString, int paraLength) {
        // Step 1. Initialize the stack through pushing a '#' at the bottom.
        CharStack tempStack = new CharStack();
        tempStack.push('#');
        char tempChar, tempPopedChar;

        // Step 2. Process the string.
        for (int i = 0; i < paraLength; i++) {
            tempChar = paraString.charAt(i);

            switch (tempChar) {
                case '(', '[', '{' -> tempStack.push(tempChar);
                case ')' -> {
                    tempPopedChar = tempStack.pop();
                    if (tempPopedChar != '(') {
                        return false;
                    } // Of if
                }
                case ']' -> {
                    tempPopedChar = tempStack.pop();
                    if (tempPopedChar != '[') {
                        return false;
                    } // Of if
                }
                case '}' -> {
                    tempPopedChar = tempStack.pop();
                    if (tempPopedChar != '{') {
                        return false;
                    } // Of if
                }
                default -> {
                }
                // Do nothing.
            }// Of switch
        } // Of for i

        tempPopedChar = tempStack.pop();
        if (tempPopedChar != '#') {
            return true;
        } // Of if

        return true;
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值