20. Valid Parentheses

来源:互联网 发布:淘宝网靠枕 编辑:程序博客网 时间:2024/06/14 04:16

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.
解析:利用栈的后进先出特点

public class Solution {    public boolean isValid(String s) {        if (s.length() % 2 != 0) {       return false;   }   char[] sArr = s.toCharArray();   HashMap<Character, Character> hm = new HashMap<Character, Character>();   hm.put(')','(');   hm.put('}','{');   hm.put(']','[');   Stack<Character> st = new Stack<Character>();   for(char c : sArr) {       if (!hm.containsKey(c)) {           st.push(c);       } else {           if (st.isEmpty() || st.pop() != hm.get(c)) {               return false;           }        }     }    return st.isEmpty();    }}
0 0
原创粉丝点击