首页 > 代码库 > Leetcode: Valid Parentheses

Leetcode: Valid Parentheses

没考虑到的情况有:input: [, expected: false; 语法上也犯了错误: 我定义的stack的泛型为char,泛型不能为primitive datatype, 

Primitive types such as char cannot be used as type parameters in Java. You need to use the wrapper type:

Stack<Character> stack =newStack<Character>(); 建议有时间再多读读泛型部分

 1 public class Solution {
 2     public boolean isValid(String s) {
 3         if (s == "") return true;
 4         Stack<Character> mystack = new Stack<Character>();
 5         int length = s.length();
 6         for (int i=0; i<length; i++){
 7             char c = s.charAt(i);
 8             if (c==‘(‘ || c==‘{‘ || c==‘[‘){
 9                 mystack.push(c);
10             }
11             if (c==‘)‘ || c==‘}‘ || c==‘]‘){
12                 if (mystack.empty()) return false;
13                 char p = mystack.pop();
14                 if (p==‘(‘ && c==‘)‘) continue;
15                 if (p==‘{‘ && c==‘}‘) continue;
16                 if (p==‘[‘ && c==‘]‘) continue;
17                 else return false;
18             }
19         }
20         if (mystack.empty()) return true;
21         else return false;
22     }
23 }