leetcode 20. Valid Parentheses
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
经典的括号问题,61B课上讲过stack方法。
class Solution { public boolean isValid(String s) { if(s.length() == 0) return true; if(s.length() % 2 != 0) return false; Map<Character,Integer> map = new HashMap<>(); map.put('(',1); map.put(')',-1); map.put('{',2); map.put('}',-2); map.put('[',3); map.put(']',-3); Stack<Character> stack = new Stack<>(); for(int i=0; i<s.length(); i++) { char a = s.charAt(i); if(map.get(a) > 0) stack.push(a); if(map.get(a) < 0) { if(stack.empty()) return false; char b = stack.pop(); if((map.get(a) + map.get(b)) != 0) return false; } } if(!stack.empty()) return false; return true; } }
解法二:同样用stack,但是没有用哈希表,而且是当指针指向左括号时,选择将相应的右括号放入stack中
public boolean isValid(String s) { Stack<Character> stack = new Stack<Character>(); for (char c : s.toCharArray()) { if (c == '(') stack.push(')'); else if (c == '{') stack.push('}'); else if (c == '[') stack.push(']'); else if (stack.isEmpty() || stack.pop() != c) return false; } return stack.isEmpty(); }