20.Valid Parentheses

題目連接:https://leetcode.com/problems/valid-parentheses/description/ide

題目大意:簡單的括號 匹配問題。spa

法一:棧,代碼以下(耗時 9ms):code

 1     public boolean isValid(String s) {
 2         char[] str = s.toCharArray();
 3         Stack<Character> stack = new Stack<Character>();
 4         for(int i = 0; i < str.length; i++) {
 5             if(str[i] == '(' || str[i] == '[' || str[i] == '{') {
 6                 stack.push(str[i]);
 7             }
 8             else if(str[i] == ')') {
 9                 if(!stack.isEmpty() && stack.pop() == '(') {
10                     continue;
11                 }
12                 else {
13                     return false;
14                 }
15             }
16             else if(str[i] == ']') {
17                 if(!stack.isEmpty() && stack.pop() == '[') {
18                     continue;
19                 }
20                 else {
21                     return false;
22                 }
23             }
24             else if(str[i] == '}') {
25                 if(!stack.isEmpty() && stack.pop() == '{') {
26                     continue;
27                 }
28                 else {
29                     return false;
30                 }
31             }
32         }
33         if(!stack.isEmpty()) {
34             return false;
35         }
36         return true;
37     }
View Code

法二(借鑑):思想略不一樣,更簡易代碼,https://leetcode.com/problems/valid-parentheses/discuss/blog

相關文章
相關標籤/搜索