用棧解決括號匹配問題。

用棧解決括號匹配問題。
“(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;
        }
    }
}

程序運行結果:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章