Leetcode: Valid Parentheses

时间:2014-05-09 09:19:01   收藏:0   阅读:252

没考虑到的情况有: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>(); 建议有时间再多读读泛型部分

bubuko.com,布布扣
 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 }
bubuko.com,布布扣

 

Leetcode: Valid Parentheses,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!