首页 > 代码库 > [Leetcode] Valid Parentheses

[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.

 

Solution:

 1 public class Solution { 2     public boolean isValid(String s) { 3         if (s == null || s.length() == 0) 4             return true; 5         if (s.length() == 1) 6             return false; 7         int N = s.length(); 8         int i = 0; 9         Stack<Character> myStack = new Stack<Character>();10         while (i < N) {11             char temp = s.charAt(i);12             if (temp == ‘(‘ || temp == ‘{‘ || temp == ‘[‘) {13                 myStack.push(temp);14                 i++;15             } else {16                 if (!myStack.isEmpty()) {17                     char t = myStack.pop();18                     if (((t == ‘(‘) && (temp == ‘)‘))19                             || ((t == ‘{‘) && (temp == ‘}‘))20                             || ((t == ‘[‘) && (temp == ‘]‘))) {21                         i++;22                     } else {23                         return false;24                     }25                 } else {26                         return false;27                 }28             }29         }30         if(myStack.isEmpty())31             return true;32         else33             return false;34     }35 }

我的代码风格太差了,贴一下大神的代码:

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

 

[Leetcode] Valid Parentheses