判断括号字符串是否有效

数组实现栈

 

package cn.bounter.dubbo.suanfa;

import java.lang.reflect.Array;

/**
 * @Description: 使用数组实现栈
 * @Date 2020/5/25
 * @Version V1.0
 **/
public class MyArrayStack {

    private T[] mArray;

    private int count;


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

    public MyArrayStack(Class 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 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;
        }

    }


}

 

你可能感兴趣的:(java基础学习)