20. 有效的括号

20. 有效的括号

题目:https://leetcode-cn.com/problems/valid-parentheses/description/

package com.test;

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

public class Lesson020 {
    public static void main(String[] args) {
        String input = "{()[]}";
        boolean res = isValid(input);
        System.out.println(res);
    }

    private static boolean isValid(String s) {
        Stack<String> stack = new Stack<>();
        // 定义左右括号字符串
        String right = ")}]";
        String left = "({[";
        // 定义左右括号对应关系
        Map<String, String> map = new HashMap<>();
        map.put("(", ")");
        map.put("{", "}");
        map.put("[", "]");
        if("".equals(s)){
            return true;
        }
        for (int i = 0; i < s.length(); i++) {
            String substring = s.substring(i, i + 1);
            // 如果是左括号就放到堆栈中
            if (left.indexOf(substring) > -1) {
                stack.push(substring);
            }
            // 如果是右括号就与堆栈中的字符串进行对比
            if (right.indexOf(substring) > -1) {
                // 堆栈里面没有内容了就返回false
                if (stack.empty()) {
                    return false;
                }
                String pop = stack.pop();
                // 字符串不一致就返回false
                if(!substring.equals(map.get(pop))){
                    return false;
                }
            }
        }
        // 全部循环完毕,堆栈里面还有内容就是false
        return stack.empty();
    }
}

 下图较简洁:

原文地址:https://www.cnblogs.com/stono/p/9475505.html