2021.10.02 - 107.有效的括号

1. 题目

在这里插入图片描述

2. 思路

(1) HashMap+栈

  • 利用HashMap存储左右括号的映射关系,利用栈先进后出的特性进行匹配。

3. 代码

import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

public class Test {
    
    
    public static void main(String[] args) {
    
    
    }
}

class Solution {
    
    
    public boolean isValid(String s) {
    
    
        if (s.length() % 2 != 0) {
    
    
            return false;
        }
        Map<Character, Character> map = new HashMap<>();
        map.put('(', ')');
        map.put('{', '}');
        map.put('[', ']');
        Deque<Character> stack = new LinkedList<>();
        char ch;
        for (int i = 0; i < s.length(); i++) {
    
    
            ch = s.charAt(i);
            if (map.containsKey(ch)) {
    
    
                stack.push(ch);
            } else if (stack.isEmpty() || map.get(stack.pop()) != ch) {
    
    
                return false;
            }
        }
        if (!stack.isEmpty()) {
    
    
            return false;
        }
        return true;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_44021223/article/details/120583373