判断字符串是否有效

前言

给定一个只包括 ‘(’ ,’)’ ,’[’ , ‘]’ ,’{’ ,’}’ 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。

比如:
输入字符串:“{ [ })”
输出:false

输入字符串:“({})”
输出:true

代码实现

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();
    }
}
发布了184 篇原创文章 · 获赞 200 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/Sophia_0331/article/details/105148952