用栈解决括号匹配问题。

用栈解决括号匹配问题。
“(XX)(YY)”:正确匹配;
“(XX(YY)”:错误匹配;
“()(XX)((YY))”:正确匹配;
解决思路:

  1. 创建一个栈用来存储左括号;
  2. 从左往右遍历字符串,拿到每一个字符;
  3. 判断该字符是不是左括号,如果是,放入栈中存储;
  4. 判断该字符是不是右括号,如果不是继续下一次循环;
  5. 如果该符号是右符号,则从栈中弹出一个元素t;
  6. 判断元素t是否为Null,如果不是,则证明有对应的左括号,如果是,则证明没有对应的左括号,
  7. 循环结束后,判断栈中还有没有剩余的左括号,如果有,则不匹配,如果没有则匹配;
    实现的代码如下:**
//创建栈
public class Stack<T>{
    //记录首结点
    private Node  head;
    //栈中元素的个数
    private int N;

    private class Node{
        //存储数据
        public T item;
        //指向下一个结点
        public Node next;

        public Node(T item,Node next){
            this.item = item;
            this.next = next;
        }
    }

    public Stack(){
        this.head = new Node(null,null);
        this.N = 0;
    }

    //判断当前栈中元素个数是否为0
    public boolean isEmpty(){
        return N == 0;
    }

    //获取栈中元素的个数
    public int size(){
        return N;
    }

    //把t元素压入栈
    public void push(T t){
       //找到首结点指向的第一个结点
        Node oldNode = head.next;
        //创建新节点
        Node newNode = new Node(t, null);
        //让首结点指向新节点
        head.next = newNode;
        //让新结点指向原来的第一个结点
        newNode.next = oldNode;
        //元素个数+1
        N++;
    }

    //弹出栈顶元素
    public T pop(){
       //找到首结点指向的第一个结点
        Node oldFirst = head.next;
        //让首结点指向原来第一个结点的下一个结点
        if(oldFirst == null){
            return null;
        }
        head.next = oldFirst.next;
        //元素个数-1
        N--;

        return oldFirst.item;
    }
}


public class BracketMatchTest {
    public static void main(String[] args) {
        String str = "X(((XX)))YY(ZZ)()";
        boolean match = isMatch(str);
        System.out.println(str+"中的括号是否匹配:"+match);
    }

    /**
     * 判断str中的括号是否匹配
     * @param str 括号组成的字符串
     * @return 他如果匹配,返回true,如果不匹配,返回false
     */

    public static boolean isMatch(String str) {
        //1.创建栈对象,用来存储左括号
        Stack<String> stack = new Stack<String>();

        //从左往右遍历遍历字符串
        for (int i = 0; i < str.length(); i++) {
            String charC = str.charAt(i)+"";

            //3.判断当前字符串是否为左括号,如果是,则把字符放入到栈中
            if(charC.equals("(")){
                stack.push(charC);
            }else if(charC.equals(")")){
                //4.继续判断当前字符是否有括号,如果是,则从栈中弹出一个左括号,
                // 并判断弹出的结果是否为null,如果为null证明没有匹配的左括号,
                String pop = stack.pop();
                if(pop == null){
                    return false;
                }
            }
        }
        //判断栈中还有没有剩余的左括号,如果有,则证明括号不匹配
        if(stack.size() == 0){
            return true;
        }else {
            return false;
        }
    }
}

程序运行结果:
在这里插入图片描述

发布了22 篇原创文章 · 获赞 21 · 访问量 1385

猜你喜欢

转载自blog.csdn.net/qq_43751200/article/details/104609582
今日推荐