题解 | #有效括号序列#
有效括号序列
https://www.nowcoder.com/practice/37548e94a270412c8b9fb85643c8ccc2
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @return bool布尔型 */ public boolean isValid (String s) { boolean matches = s.matches("[^\\{\\[\\(\\}\\]\\)]");//判断字符串是否有除了给定括号之外的字符 if (matches == true) { return false; } int count = 0; // write code here ArrayList<Character> list = new ArrayList(); for (int i = 0; i < s.length(); i++) { if (s.charAt(i)=='['|| s.charAt(i)=='{'|| s.charAt(i)=='('){ list.add(s.charAt(i));//把左括号添加到list集合 count++;//集合里的左元素括号个数 } else { //如果第一个就是右括号直接返回false if (count == 0) { return false; } //判断右括号是否和左括号匹配 不匹配直接终止循环 if (match(s.charAt(i), list.get(count - 1))){ list.remove(count - 1);//括号匹配 删除最右边的左括号 count--;//集合里左括号个数减一 }else{ break; } } } //集合里左括号全部成功匹配弹出 if (count == 0) return true; else return false; } public static boolean match(char right, char left) { if (right == ']' && left == '[') return true; if (right == '}' && left == '{') return true; if (right == ')' && left == '(') return true; return false; } }