给定一个只包括 '('
,')'
,'{'
,'}'
,'['
,']'
的字符串 s
,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
- 每个右括号都有一个对应的相同类型的左括号。
-
示例 1:
输入:s = "()"
输出:true
示例 2:
输入:s = "()[]{}"
输出:true
示例 3:
输入:s = "(]"
输出:false
示例 4:
输入:s = "([])"
输出:true
-
class Solution { public static boolean isValid(String s) { if(s.length()%2 !=0){ return Boolean.FALSE; } Map<Character,Character> map = new HashMap<Character,Character>(); map.put(')','('); map.put('}','{'); map.put(']','['); Stack<Character> stack = new Stack<>(); for(int index =0;index<s.length();index++){ if(stack.isEmpty()){ stack.push(s.charAt(index)); continue; } Character peek = stack.peek(); if(map.get(s.charAt(index)) == peek){ stack.pop(); }else{ stack.push(s.charAt(index)); } } return stack.isEmpty()?Boolean.TRUE:Boolean.FALSE; } }