Determining whether a valid string

Foreword

Includes only a given '(', ')' string, '[', ']', '{', '}', it is determined whether the string is valid.
Valid string to be fulfilled:
the left bracket must be of the same type of closed right parenthesis.
Left parenthesis must be closed in the correct order.
Note the empty string can be considered a valid string.

For example:
Input string: "{[})"
Output: false

Input string: "({})"
Output: true

Code

package com.algorithmic.Character;

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

public class IsCharacter {

    public static void main(String[] args) throws Exception {
        Boolean bool= isValid("([(])");
//        Boolean bool= isValid("");
        System.out.println("判断的结果:========"+bool);
    }


    public static boolean isValid(String s)throws Exception {
        Stack<Character> ns=new Stack<Character>();
        Map<Character,Character> m=new HashMap<Character,Character>();
        m.put(')','(');
        m.put('}','{');
        m.put(']','[');
        for(int i=0;i<s.length();i++){
            char tmp=s.charAt(i);
            if(tmp=='(' || tmp=='{' || tmp=='[') {
                ns.push(s.charAt(i));
            }else{
                char temp=m.get(tmp);
                if(ns.isEmpty()){
                    return false;
                }
                if(temp!=ns.pop()){
                    return false;
                }
            }
        }
        return ns.isEmpty();
    }
}
Published 184 original articles · won praise 200 · views 80000 +

Guess you like

Origin blog.csdn.net/Sophia_0331/article/details/105148952