Leetcode: Valid Parentheses


Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.


The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

 

没考虑到的情况有: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 }

 另一种做法:

 1 public boolean isValid(String s) {

 2     if(s==null || s.length()==0)

 3         return true;

 4     LinkedList<Character> stack = new LinkedList<Character>();

 5     for(int i=0;i<s.length();i++)

 6     {

 7         switch(s.charAt(i))

 8         {

 9             case '(':

10             case '{':

11             case '[':

12                 stack.push(s.charAt(i));

13                 break;

14             case ')':

15                 if(stack.isEmpty() || stack.pop()!='(')

16                     return false;

17                 break;

18             case '}':

19                 if(stack.isEmpty() || stack.pop()!='{')

20                     return false;

21                 break;

22             case ']':

23                 if(stack.isEmpty() || stack.pop()!='[')

24                     return false;

25                 break; 

26             default:

27                 break;

28         }

29     }

30     if(stack.isEmpty())

31         return true;

32     return false;

33 }

 

你可能感兴趣的:(LeetCode)