华为上机练习题--括号匹配检測

版权声明:本文为博主原创文章,未经博主同意不得转载。 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;
    }
}


posted @ 2018-11-15 19:19  ldxsuanfa  阅读(181)  评论(0编辑  收藏  举报