博客搬家啦,更多干货 https://blog.csdn.net/qq_2816...

问题: 输入一系列的括号,判断格式是否正确

这里直接用java写好的栈,栈的实现较简单,不单独手写栈了,可以用数组实现栈,也可以用链表实现

import java.util.Collection;
import java.util.HashMap;
import java.util.Set;
import java.util.Stack;

public class BracketMatch {

    /**
     * 用栈解决括号匹配的类似问题
     *
     */

    public boolean isMatch(String str){
        char[] c = str.toCharArray();
        Stack<Character> stack = new Stack<>();

        HashMap<Character, Character> hashMap = new HashMap<Character, Character>(){
            {
                put(')','(');
                put('}','{');
                put(']','[');
                put('>','<');
            }
        };

        Set<Character> keySet = hashMap.keySet();
        Collection<Character> vC = hashMap.values();

        for(char s : c){
            if(vC.contains(s)){
                stack.push(s);
            }else if(keySet.contains(s)){
                if(stack.pop() != hashMap.get(s)){
                    return false;
                }
            }
        }
        return stack.empty();
    }

}

Devilu
85 声望4 粉丝

just a newbie