Leetcode Valid Parentheses

来源:互联网 发布:苹果点位图软件 编辑:程序博客网 时间:2024/05/17 20:26

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.


Difficulty: Easy


public class Solution {    public boolean isValid(String s) {        int len = s.length();        if(len%2 == 1)            return false;        HashMap<Character, Character> hm = new HashMap<Character, Character>();        hm.put('(', ')');        hm.put('[', ']');        hm.put('{', '}');        Stack<Character> st = new Stack<Character>();        for(int i = 0; i < len; i++){            if(st.empty()){                st.push(s.charAt(i));            }            else{                if(hm.containsKey(st.peek()) && hm.get(st.peek()) == s.charAt(i)){                    st.pop();                }                else{                    st.push(s.charAt(i));                }            }        }                return st.empty();    }}


0 0