149.Valid Parentheses(有效的括号)

题目:

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

给定一个只包含字符'(',')','{','}','['和']'的字符串,确定输入字符串是否有效。

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.必须使用相同类型的括号关闭左括号。
  2. Open brackets must be closed in the correct order.必须以正确的顺序关闭左括号。

Note that an empty string is also considered valid.

请注意,空字符串也被视为有效。

Example 1:

Input: "()"
Output: true

Example 2:

Input: "()[]{}"
Output: true

Example 3:

Input: "(]"
Output: false

Example 4:

Input: "([)]"
Output: false

Example 5:

Input: "{[]}"
Output: true

解答:

自己写的:

 1 class Solution {
 2     public boolean isValid(String s) {
 3         if(s==null || s.length()==0) return true;
 4         Stack<Character> stack=new Stack<>();
 5         for(int i=0;i<s.length();i++){
 6             if(s.charAt(i)=='(' || s.charAt(i)=='[' || s.charAt(i)=='{'){
 7                 stack.push(s.charAt(i));
 8             }else if(s.charAt(i)==')' || s.charAt(i)==']' || s.charAt(i)=='}'){
 9                 if(stack.isEmpty()){
10                     return false;
11                 }else{
12                     char c=stack.peek();
13                     char b=match(c);
14                     if(b==s.charAt(i))
15                         stack.pop();
16                     else
17                         return false;
18                 }
19             }
20         }
21         return stack.isEmpty();
22     }
23     
24     private char match(Character c){
25         char res;
26         if(c=='(')
27             res=')';
28         else if(c=='[')
29             res=']';
30         else
31             res='}';
32         return res;
33     }
34 }

简洁:

 1 class Solution {
 2     public boolean isValid(String s) {
 3         Stack<Character> stack=new Stack<>();
 4         for(char c:s.toCharArray()){
 5             if(c=='(')
 6                 stack.push(')');
 7             else if(c=='[')
 8                 stack.push(']');
 9             else if(c=='{')
10                 stack.push('}');
11             else if(stack.isEmpty() || stack.pop()!=c)
12                 return false;
13         }
14         return stack.isEmpty();
15     }
16 }

详解:

典型的用栈实现的问题

posted @ 2018-09-09 11:34  chan_ai_chao  阅读(142)  评论(0编辑  收藏  举报