题解 | #有效括号序列#
有效括号序列
https://www.nowcoder.com/practice/37548e94a270412c8b9fb85643c8ccc2
import java.util.*; public class Solution { /** * * @param s string字符串 * @return bool布尔型 */ public boolean isValid (String s) { Stack<Character> stack = new Stack<>(); // write code here if (s == null || s.length() < 2) { return false; } char[] chars = s.toCharArray(); for (int i = 0; i < chars.length; i++) { // 成对则弹出 if (chars[i] == ')') { if (stack.isEmpty() || stack.pop() != '(') { return false; } } else if (chars[i] == '}') { if (stack.isEmpty() || stack.pop() != '{') { return false; } } else if (chars[i] == ']') { if (stack.isEmpty() || stack.pop() != '[') { return false; } } else { stack.push(chars[i]); } } // 只有栈为空,才说明成对出现 return stack.isEmpty(); } }