欢迎光临散文网 会员登陆 & 注册

火大教育web3.0应用工程师培养计划

2022-10-05 23:51 作者:绿兔子2  | 我要投稿

计算匹配的括号

public class ParenthesisMatching {    // [] => valid    // {[]} => valid    // [(]) => invalid    public static void main(String[] args) {        System.out.println(isValid("[]"));        System.out.println(isValid("{[]}"));        System.out.println(isValid("{[]}()"));        System.out.println(isValid("{[]}([)]"));    }    public static boolean isValid(String string) {        Map<Character, Character> bracketMap = new HashMap<>();        bracketMap.put('[', ']');        bracketMap.put('(', ')');        bracketMap.put('{', '}');        if (string == null || string.isEmpty()) {            return true;        }        Deque<Character> stack = new ArrayDeque<>();        char[] chars = string.toCharArray();        for (char ch : chars) {            if ("[{(".indexOf(ch) >= 0) {                stack.push(ch);                continue;            }            Character head = stack.peek();            if ("]})".indexOf(ch) >= 0) {                if (head != null && ch == bracketMap.get(head)) {                    stack.pop();                    continue;                } else {                    return false;                }            }            throw new IllegalArgumentException("参数非法:" + string);        }        return stack.isEmpty();    }}


火大教育web3.0应用工程师培养计划的评论 (共 条)

分享到微博请遵守国家法律