• 判断字符串中括号是否成对存在


    判断字符串中括号是否成对存在

    比如:

    ()()(())  OK

    ()[]{}{([])}  OK

    ((())]  NO

    思路:遇到左括号入栈,遇到右括号,将左括号出栈(对应的右括号要存在)

    import java.util.HashMap;
    import java.util.Map;
    import java.util.Stack;
    
    public class BracketMatching {
        // pair以右括号为key, 左括号为值
        private Map<Character, Character> pair = null;
    
        public  BracketMatching()
        {
            pair = new HashMap<Character, Character>();
            pair.put(')', '(');
            pair.put('}', '{');
            pair.put(']', '[');
        }
    
        public boolean isMatch(String s)
        {
            Stack<Character> sc = new Stack<Character>();
            for (int i = 0; i < s.length(); i++)
            {
                Character ch = s.charAt(i);
                if (pair.containsValue(ch))// 如果是左括号,放入栈中
                {
                    sc.push(ch);
                } else if (pair.containsKey(ch)) // 如果是右括号
                {
                    if (sc.empty()) // 栈为空,栈头没有字符与右括号匹配
                    {
                        return false;
                    }
                    // 栈不为空,栈头字符与右括号匹配
                    if (sc.peek() == pair.get(ch))
                    {
                        sc.pop();
                    } else //网上许多列子没有这里的else代码块,导致({}[]]])会被判断为true
                    { // 栈不为空,栈头字符不与右括号匹配
                        return false;
                    }
                }
    
            }
    
            return sc.empty() ? true : false;
        }
    
        public static void main(String[] args)
        {
            BracketMatching judger = new BracketMatching();
            System.out.println(judger.isMatch("(***)-[{-------}]")); //true
            System.out.println(judger.isMatch("(2+4)*a[5]")); //true
            System.out.println(judger.isMatch("({}[]]])")); //false
            System.out.println(judger.isMatch("())))")); //false
            System.out.println(judger.isMatch("((()")); //false
            System.out.println(judger.isMatch("(){[[]]}")); //true
        }
    
    
    }
  • 相关阅读:
    CMSIS_OS中osMailPut 和 osMessagePut 的问题
    网络:W5500抓包TCP segment of a reassembled PDU
    网络:W5500 UDP数据包格式注意事项
    笔记:把编译时间加入到目标文件
    笔记:git和码云
    笔记:git基本操作
    FreeRtos堆栈检测应用
    一个由自增运算符以及C语法顺序细节引起的bug
    高级文件操作
    linux 权限相关
  • 原文地址:https://www.cnblogs.com/duange/p/8832888.html
Copyright © 2020-2023  润新知