判斷括號字符串是否有效

數組實現棧

 

package cn.bounter.dubbo.suanfa;

import java.lang.reflect.Array;

/**
 * @Description: 使用數組實現棧
 * @Date 2020/5/25
 * @Version V1.0
 **/
public class MyArrayStack<T> {

    private T[] mArray;

    private int count;


    public MyArrayStack(Class<T> type, int count) {
        this.mArray = (T[]) Array.newInstance(type,count);
        this.count = 0;
    }

    public MyArrayStack(Class<T> type) {
        this(type, 12);
    }

    // 將val添加到棧中
    public void push(T val) {
        mArray[count++] = val;
    }

    // 返回“棧頂元素值”
    public T peek() {
        return mArray[count-1];
    }

    // 返回“棧頂元素值”,並刪除“棧頂元素”
    public T pop() {
        T ret = mArray[count-1];
        count--;
        return ret;
    }

    // 返回“棧”的大小
    public int size() {
        return count;
    }

    // 返回“棧”是否爲空
    public boolean isEmpty() {
        return size()==0;
    }

    public static void main(String[] args) {




    }


}

 

package cn.bounter.dubbo.suanfa;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 括號匹配
 * @Date 2020/5/25
 * @Version V1.0
 **/
public class KuoHaoMatch {


    public static void main(String[] args) {
        String case1="()";
        //輸出: true
        String case2="([])";
        //輸出: true
        String case3="()[]{}";
        //輸出: true
        String case4="])(]";
        //輸出: false
        String case5="(]";
        //輸出: false
        String case6="([)]";
        //輸出: false
        String case7="(([])";


        System.out.println(isValid(case1));
        System.out.println(isValid(case2));
        System.out.println(isValid(case3));
        System.out.println(isValid(case4));
        System.out.println(isValid(case5));
        System.out.println(isValid(case6));
        System.out.println(isValid(case7));

    }

    private static boolean isValid(String case1) {
        Map<Character,Character> map =new HashMap();
        map.put(')','(');
        map.put(']','[');
        map.put('}','{');

        MyArrayStack stack=new MyArrayStack(Character.class);
        for (Character temp: case1.toCharArray()) {
            if (map.containsKey(temp)){
                //1、case4直接爲空
                if(stack.isEmpty()){
                    return false;
                }
                Character peek = (char) stack.peek();
                if(peek.equals(map.get(temp))){
                    stack.pop();
                }else {
                    //2、case5,case6直接爲空
                    return false;
                }
            }else {
                stack.push(temp);
            }
        }
        if(stack.isEmpty()){
            return true;
        }else {
            //3、case7
            return false;
        }

    }


}

 

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