20. 有效的括号

image.png

  1. public static boolean isValid(String s) {
  2. if (StringUtils.isEmpty(s)) {
  3. return false;
  4. }
  5. char[] chars = s.toCharArray();
  6. Stack<Character> stack = new Stack<Character>();
  7. for (char c : chars) {
  8. if (stack.isEmpty()) {
  9. stack.push(c);
  10. }else {
  11. if (match(stack.peek(), c)) {
  12. stack.pop();
  13. } else {
  14. stack.push(c);
  15. }
  16. }
  17. }
  18. return stack.isEmpty();
  19. }
  20. private static boolean match(char a, char b) {
  21. if (a == '[' && b == ']') {
  22. return true;
  23. }
  24. if (a == '(' && b == ')') {
  25. return true;
  26. }
  27. if (a == '{' && b == '}') {
  28. return true;
  29. }
  30. return false;
  31. }