描述

20. 有效的括号 - 力扣(Leetcode)

分析

先分析有哪几种非有效的括号

  1. 左边多了括号匹配1
  2. 左右不匹配的括号匹配2
  3. 右边多了括号匹配3

实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import java.util.Scanner;
import java.util.Stack;

//有效的括号20
public 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();
}
}

总结