题解 | #有效括号序列#
有效括号序列
https://www.nowcoder.com/practice/37548e94a270412c8b9fb85643c8ccc2
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @return bool布尔型 */ public boolean isValid (String s) { // write code here // 思路:从左往右,遇到“({[” 压栈,遇到“)}]” 就从栈中弹出元素和当前元素组合后与括号对“{}”、“[]”、“()”比较,相同则继续,不同则return false; 然后遍历到最后需要再判断下当前栈是否为空,为空则说明符合要求。 String[] arr = s.split(""); if(arr.length % 2 != 0) { return false; } // Deque<String> que = new Deque<String>(); Stack<String> stack = new Stack<String>(); for(int i=0;i<arr.length;i++) { String ch = arr[i]; // System.out.println("ch-:" + ch + ",peek:" + stack.peek()); if(")]}".indexOf(ch) >=0) { if(stack.isEmpty()) { return false; } if(!Arrays.asList("()","[]","{}").contains(stack.pop().concat(ch))) { return false; } } else { stack.push(ch); } } if(!stack.isEmpty()) { return false; } return true; } }