LeetCode 有效的括号 Java堆栈解决

我记得我看浙大数据结构的时候,何老师有提到过用类似的堆栈可以解决编译器的有关问题。而且当时还有一道运算类的习题,偏偏我做题时没有想到。还是要多刷题,长见识。

 1 package fanlu.leetcode;
 2 
 3 import java.util.Stack;
 4 
 5 public class IsBraketValid {
 6 
 7     public static boolean isValid(String s) {
 8         if (s.isEmpty()) {
 9             return true;
10         }
11 
12         Stack<Character> stack = new Stack<>(); //  创建一个堆栈
13 
14         for (char c : s.toCharArray()) {
15             if (c == '(') {
16                 stack.push(')');
17             } else if (c == '[') {
18                 stack.push(']');
19             } else if (c == '{') {
20                 stack.push('}');
21             } else if (stack.empty() || c != stack.pop()) {
22                 return false;
23             }
24         }
25 
26         return stack.empty();
27 
28     }
29 
30     public static void main(String[] args) {
31         String str = "()[]{}";
32         System.out.println(isValid(str));
33     }
34 
35 }

猜你喜欢

转载自www.cnblogs.com/fanlumaster/p/12595342.html
今日推荐