Leetcode 20. Valid Parentheses

题目描述:返回一个字符串是否符合括号匹配。({)}不符合,空为True.

题目链接:Leetcode 20. Valid Parentheses

思路就是用栈,弹栈压栈的判断就可以了。

代码如下

import java.util.HashMap;
import java.util.Arrays;
import java.util.LinkedList;

class Solution {
    public boolean isValid(String s) {
        if (s.length() == 0) {
            return true;
        }
        HashMap<Character, Character> hm = new HashMap();
        hm.put(')', '(');
        hm.put('}', '{');
        hm.put(']', '[');
        LinkedList<Character> stack = new LinkedList<>();
        int idx = 0;
        while (idx < s.length()) {
            if (hm.containsValue(s.charAt(idx))) {
                stack.add(s.charAt(idx));
            }else{
                if (stack.size() == 0) {
                return false;
            }
            if (stack.getLast() != hm.get(s.charAt(idx))) {
                return false;
            }
            stack.removeLast();
            }
            
            idx++;
        }
        
        boolean ans = stack.size() == 0 ? true : false;
        return ans;
        
        
    }
}
from collections import defaultdict
class Solution:
    def isValid(self, s: str) -> bool:
        if not s:
            return True
        hm2 = {")":"(","}":"{","]":"["}
        idx = 0
        stack = []
        while(idx < len(s)):
            if s[idx] in hm2.values():
                stack.append(s[idx])
            else:
                if not stack:
                    return False
                if stack[-1] != hm2[s[idx]]:
                    return False
                stack.pop()  #是匹配的就推出
            idx += 1
        return True if not stack else False            
                

参考链接

Leetcode 20. Valid Parentheses