Valid Parentheses

来源:互联网 发布:手机淘宝店怎样发货 编辑:程序博客网 时间:2024/05/29 14:33

题目:

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

思路:

用哈希表来存字符之间的配对关系,然后其实就是一个进栈出栈的过程(配对就出栈),最后栈为空返回true,否则false。

public class Solution {    public boolean isValid(String s) {        if (s == null || s.length() == 0) {            return true;        }        HashMap<Character,Character> hashMap = new HashMap<>();        hashMap.put(')','(');        hashMap.put(']','[');        hashMap.put('}','{');        Stack<Character> stack = new Stack<>();        for (int i = 0;i < s.length();i++) {            if (!stack.empty()) {                if (hashMap.get(s.charAt(i)) == stack.peek()) {                    stack.pop();                } else {                    stack.push(s.charAt(i));                }            } else {                stack.push(s.charAt(i));            }        }        return stack.empty()?true:false;    }}



0 0