【leetcode】20. 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.

解题分析:

这是之前实习笔试的时候遇到的一道题,一个典型的栈的应用例子。很容易实现,唯一可能忽略的地方是:不匹配的条件有三个:

  1. 字符串扫描完,栈不为空
  2. 栈顶的括号与扫描到的不匹配
  3. 运行过程中栈为空,淡扫面到的字符时),],}

尤其第三个条件很容易被忽略

具体代码:

 1 public class Solution {
 2   public static boolean isValid(String s) {
 3         if(s==null||s.length()==0||(s.length()&1)!=0){
 4             return false;
 5         }
 6         Stack<Character> stack =new Stack<Character>();
 7         for(int i=0;i<s.length();i++){
 8             char ch =s.charAt(i);
 9             if(ch=='('||ch=='{'||ch=='['){
10                 stack.push(ch);
11             }
12             else if(ch==')'){
13                 
14                 if(stack.size()>0&&stack.peek()=='('){
15                     stack.pop();
16                 }
17                 else{
18                     return false;
19                 }
20             }
21             else if(ch==']'){
22                 if(stack.size()>0&&stack.peek()=='['){
23                     stack.pop();
24                 }
25                 else{
26                     return false;
27                 }
28             }
29             else if(ch=='}'){
30                 if(stack.size()>0&&stack.peek()=='{'){
31                     stack.pop();
32                 }
33                 else{
34                     return false;
35                 }
36             }
37             else
38                 ;
39         }
40         if(stack.size()>0)
41             return false;
42         return true;
43     }
44 }
原文地址:https://www.cnblogs.com/godlei/p/5642153.html