码迷,mamicode.com
首页 > 其他好文 > 详细

[Leetcode] Valid Parentheses

时间:2014-11-15 15:23:46      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   ar   os   sp   for   div   

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         else
33             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

标签:style   blog   io   color   ar   os   sp   for   div   

原文地址:http://www.cnblogs.com/Phoebe815/p/4099255.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!