描述 20. 有效的括号 - 力扣(Leetcode) 分析 先分析有哪几种非有效的括号 左边多了 左右不匹配的 右边多了 实现 1234567891011121314151617181920212223242526272829303132333435363738import java.util.Scanner;import java.util.Stack;//有效的括号20public class ValidParentheses20 { public static void main(String[] args){ Scanner input = new Scanner(System.in); if (new Solution().isValid(input.nextLine())) { System.out.println("yes"); } else { System.out.println("no"); } }}class Solution { public boolean isValid(String s) { if (s.length() % 2 != 0) { //字符串为奇数,坑定不会yes return false; } Stack<Character> stack = new Stack<>(); for(char item : s.toCharArray()){ if (item == '(') { stack.push(')'); } else if (item =='[') { stack.push(']'); }else if (item == '{') { stack.push('}'); }else if (stack.isEmpty() || stack.peek() != item){ return false; }else { stack.pop(); } } return stack.isEmpty(); }} 总结