20. Valid Parentheses
Easy
2700136FavoriteShare
Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
Input: "()" Output: true
Example 2:
Input: "()[]{}" Output: true
Example 3:
Input: "(]" Output: false
Example 4:
Input: "([)]" Output: false
Example 5:
Input: "{[]}" Output: true
1. 使用栈结构
/** * 使用栈结构 * @param s * @return */ public boolean isValid(String s){ Stack<Character> stack = new Stack<>(); Map<Character,Character> map = new HashMap<>(); char[] chars = s.toCharArray(); map.put(')','('); map.put('}','{'); map.put(']','['); for(int i=0;i < s.length();i++){ if(!map.containsKey(chars[i])) { //为左括号时直接入栈 stack.push(chars[i]); }else{ //为右括号时,如果栈为空或者栈顶与该括号类型不匹配返回false if(stack.empty() || map.get(chars[i]) != stack.pop()){ return false; } } } //字符串遍历完毕后,如果栈为空返回true,反之返回false return stack.empty(); } }
2. 替换法
public boolean isValid(String s){ int length; do{ length = s.length(); s = s.replace("()","").replace("[]","").replace("{}",""); }while(length != s.length()); return s.length() == 0; }