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.
import java.util.HashMap; import java.util.Stack; /** * Created by lxw, liwei4939@126.com on 2018/3/4. */ public class ValidParentheses { public boolean isValid(String s){ if (s == null || s.length() % 2 == 1){ return false; } HashMap<Character, Character> map = new HashMap<>(); map.put('(', ')'); map.put('[', ']'); map.put('{', '}'); Stack<Character> stack = new Stack<>(); for (int i = 0; i < s.length(); i++){ char c = s.charAt(i); if (map.containsKey(c)){ stack.push(c); } else if (map.containsValue(c)){ if (!stack.empty() && map.get(stack.peek()) == c){ stack.pop(); } } else { return false; } } return stack.empty(); } public static void main(String[] args){ ValidParentheses tmp = new ValidParentheses(); String str = "([)]"; System.out.println(tmp.isValid(str)); } }