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.

solution:

楼主曾经很天真的:

public class Valid_Parentheses {
   public static boolean vaildparenthess(String s) {
       boolean flag=true;
       if(s.charAt(0)-')'==0 ||s.charAt(0)-']'==0||s.charAt(0)-'}'==0){
           return false;
       }else{
           for (int i = 1; i < s.length(); i++) {
            if(s.charAt(i)-'('==0){
                if(s.charAt(i+1)-')'!=0)
                    flag=false;
            }
            if(s.charAt(i)-'['==0){
                if(s.charAt(i+1)-']'!=0)
                    flag=false;
            }
            if(s.charAt(i)-'{'==0){
                if(s.charAt(i+1)-'}'!=0)
                    flag=false;
            }
            if(s.charAt(i)-')'==0){
                if(s.charAt(i-1)-'('!=0)
                    flag=false;
            }
            if(s.charAt(i)-']'==0){
                if(s.charAt(i-1)-'['!=0)
                    flag=false;
            }
            if(s.charAt(i)-'}'==0){
                if(s.charAt(i+1)-'{'!=0)
                    flag=false;
            }
        }
       return flag;
    }
    
}
    public static void main(String[] args) {
        // TODO Auto-generated method stub
     String s="[]";
     System.out.println(vaildparenthess(s));
    }

}

但是,楼主这个愚蠢的人类!!!(≧∇≦)

明明用stack可以很方便的解决!!first in last out!!

package leetcode2;

import java.util.Stack;

public class valid_parenthese {
    public static boolean vaildparenthess(String s) {
       boolean flag=true;
       Stack<Character> st=new Stack<Character>();
       if(s==null){
           return false;
       }
       for(int i=0;i<s.length();i++){
           if(s.charAt(i)=='('||s.charAt(i)=='{'||s.charAt(i)=='['){
               st.push(s.charAt(i));
           }else if(s.charAt(i)==')'){
               if(st.pop()!='(')
                   flag=false;
           }else if(s.charAt(i)==']'){
               if(st.pop()!='[')
                   flag=false;
           }else if(s.charAt(i)=='}'){
               if(st.pop()!='{')
                   flag=false;
           }
          
       }
       if(!st.isEmpty()){
           flag=false;
       }
       return flag;
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
    String string="{()()}";
    System.out.println(vaildparenthess(string));
    }

}
原文地址:https://www.cnblogs.com/joannacode/p/4389655.html