import java.util.*; public class Solution { /** * * @param s string字符串 * @return bool布尔型 */ public boolean isValid (String s) { if (s == null || s.length() == 0) { return false; } Stack<Character> stack = new Stack<>(); char[] chars = s.toCharArray(); for (int i = 0; i < chars.length; i++) { if ('(' == chars[i]) { stack.push(')'); } else if ('[' == chars[i]) { stack.push(']'); } else if ('{' == chars[i]) { stack.push('}'); } else { if (stack.isEmpty() || stack.pop() != chars[i]) { return false; } } } //最后可能栈里还有元素 代表非合法括号序列 return stack.isEmpty(); } }