zoukankan      html  css  js  c++  java
  • 华为上机练习题--括号匹配检測

    版权声明:本文为博主原创文章,未经博主同意不得转载。 https://blog.csdn.net/zlw420123/article/details/35649497

    题目:

    输入一串字符串。当中有普通的字符与括号组成(包含‘(’、‘)’、‘[’,']'),要求验证括号是否匹配。假设匹配则输出0、否则输出1.

            Smple input:dfa(sdf)df[dfds(dfd)]    Smple outPut:0


    分析: 相似于括号字符匹配这类的问题, 我们能够模拟栈的操作来进行验证, 这样问题就简单了。 就是栈的操作


    代码例如以下:

    package com.wenj.test;

    import java.util.ArrayList;
    import java.util.List;

    public class TestMatchKuohao {
        
        public static void main(String args[]){
            String strIn = "dfa(sdf)df[dfds(dfd)]";
            
            TestMatchKuohao tm = new TestMatchKuohao();
            System.out.println(tm.matchKuohao(strIn));
        }
        
        public int matchKuohao(String strIn){
            if("" == strIn || null == strIn){//空串默认不配
                return 1;
            }
            String strTemp = strIn;
            char[] strC = strTemp.toCharArray();
            
            List<Character> cL = new ArrayList<Character>();
            for(int i=0; i<strC.length; i++){
                char temp = strC[i];
                switch(temp){
                case '(':
                    cL.add(temp);
                    break;
                case '[':
                    cL.add(temp);
                    break;
                case ')': //遇到右括号则出栈
                    if(cL.size() == 0){//假设栈空则说明括号匹配不上,直接返回1
                        return 1;
                    }else{
                        char tempC = cL.get(cL.size()-1);
                        if('(' == tempC){
                            cL.remove(cL.size()-1); //做出栈操作
                        }else{
                            return 1;
                        }
                    }
                    break;
                case ']':
                    if(cL.size() == 0){
                        return 1;
                    }else{
                        char tempC = cL.get(cL.size()-1);
                        if('[' == tempC){
                            cL.remove(cL.size()-1);
                        }else{
                            return 1;
                        }
                    }
                    break;
                default:
                    break;
                }
            }
            
            if(cL.size() == 0)
                return 0;
            else
                return 1;
        }
    }


  • 相关阅读:
    如何查看Android SDK源码版本
    迁移 Express 到函数计算
    阿里云安全运营中心:DDoS攻击趁虚而入,通过代理攻击已成常态
    Schedulerx2.0支持应用级别资源管理和任务优先级
    Serverless 解惑——函数计算如何安装字体
    一遇到复杂分析查询就卡顿?MySQL分析实例了解一下
    浅谈企业的数据资产管理
    大咖说备份 | 云,让灾备更简单
    急速上线 Serverless 钉钉机器人“防疫精灵”
    Alibaba Cloud Linux 2 LTS 正式发布,提供更高性能和更多保障
  • 原文地址:https://www.cnblogs.com/ldxsuanfa/p/9965571.html
Copyright © 2011-2022 走看看