華為上機練習題--括弧匹配檢測

來源:互聯網
上載者:User

題目:

輸入一串字串,其中有普通的字元與括弧組成(包括‘(’、‘)’、‘[’,']'),要求驗證括弧是否匹配,如果匹配則輸出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;
    }
}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.