zoukankan      html  css  js  c++  java
  • 判断字符串中括号是否成对存在

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

    比如:

    ()()(())  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
        }
    
    
    }
  • 相关阅读:
    Android Touch事件相关源码【Android SourceCode 2.3.6】
    使用方式比较优雅的代码集合
    Android系统中是否开启定位及定位模式的判断
    Android中软键盘展示、EditText焦点获取及windowSoftInputMode属性探究
    删除rz上传失败乱码的文件
    linux mysql 操作命令
    linux下端口被占用
    linux环境搭建记录
    ibatis 批量插入数据
    jQuery id模糊 选择器 批量处理
  • 原文地址:https://www.cnblogs.com/duange/p/8832888.html
Copyright © 2011-2022 走看看