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.
方法一、找到第一个右括号,然后和左边的字符一起借助哈希表映射,判断是否成对。
1 public static boolean isValid(String s) { 2 if(s.length()<2 || s.length()%2==1) 3 return false; 4 Mapmap=new HashMap (); 5 map.put('(', 1); 6 map.put(')', 9); 7 map.put('{', 2); 8 map.put('}', 8); 9 map.put('[', 3);10 map.put(']', 7);11 boolean result=true;12 for(int i=0;i
方法二,栈
public boolean isValid(String s) { if(s.length()<1 || s.length()%2!=0) return false; Stackstack=new Stack (); for(int i=0;i