LeetCode--20--easy--Valid Parentheses

本文介绍了一种使用栈数据结构来验证括号序列是否有效的算法。通过遍历输入字符串,利用哈希映射匹配左右括号,确保每对括号正确闭合且顺序正确。文章提供了详细的代码实现及示例。
package com.app.main.LeetCode;

/**
 * Created with IDEA
 * author:Dingsheng Huang
 * Date:2019/6/28
 * Time:下午8:19
 */

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

/**
 * Given a string containing just the characters '(', ')', '{', '}', '[' and ']',
 * determine if the input string is valid.
 *
 * An input string is valid if:
 *
 * Open brackets must be closed by the same type of brackets.
 * Open brackets must be closed in the correct order.
 * Note that an empty string is also considered valid.
 *
 * Example 1:
 *
 * Input: "()"
 * Output: true
 * Example 2:
 *
 * Input: "()[]{}"
 * Output: true
 * Example 3:
 *
 * Input: "(]"
 * Output: false
 * Example 4:
 *
 * Input: "([)]"
 * Output: false
 * Example 5:
 *
 * Input: "{[]}"
 * Output: true
 */
public class ValidParentheses {

    /**
     * 思路: 用栈模拟符号匹配
     * @param s
     * @return
     */
    public boolean isValid(String s) {

        Map<String, String> map  = new HashMap<>();
        map.put("(", ")");
        map.put("[", "]");
        map.put("{", "}");

        Stack<String> stack = new Stack();

        // 遍历字符串
        for (int i = 0; i < s.length(); i++) {
            String item = String.valueOf(s.charAt(i));

            //  当前字符属于“左”括号类型,则入栈
            if (map.containsKey(item)) {
                stack.push(item);
            } else {
                // 当前字符属于 "右" 括号类型,则判断如果是第一个字符,则必定不合法。
                if (stack.empty()) {
                    return false;
                }
                // 取栈顶字符"右"括号匹配,匹配不上,则不合法
                String popItem = stack.pop();
                if (!map.get(popItem).equals(item)) {
                    return false;
                }
            }
        }
        // 遍历完字符串、且栈为空,则合法
        return stack.empty();
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值