ValidParentheses之Java實(shí)現(xiàn)

一、題目

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
??Open brackets must be closed by the same type of brackets.
??Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
??Input: "()"
??Output: true
Example 2:
??Input: "()[]{}"
??Output: true
Example 3:
??Input: "(]"
??Output: false
Example 4:
??Input: "([)]"
??Output: false
Example 5:
??Input: "{[]}"
??Output: true

創(chuàng)新互聯(lián)建站服務(wù)項(xiàng)目包括太倉(cāng)網(wǎng)站建設(shè)、太倉(cāng)網(wǎng)站制作、太倉(cāng)網(wǎng)頁(yè)制作以及太倉(cāng)網(wǎng)絡(luò)營(yíng)銷策劃等。多年來(lái),我們專注于互聯(lián)網(wǎng)行業(yè),利用自身積累的技術(shù)優(yōu)勢(shì)、行業(yè)經(jīng)驗(yàn)、深度合作伙伴關(guān)系等,向廣大中小型企業(yè)、政府機(jī)構(gòu)等提供互聯(lián)網(wǎng)行業(yè)的解決方案,太倉(cāng)網(wǎng)站推廣取得了明顯的社會(huì)效益與經(jīng)濟(jì)效益。目前,我們服務(wù)的客戶以成都為中心已經(jīng)輻射到太倉(cāng)省份的部分城市,未來(lái)相信會(huì)繼續(xù)擴(kuò)大服務(wù)區(qū)域并繼續(xù)獲得客戶的支持與信任!

二、解題思路

1、利用List集合實(shí)現(xiàn)一個(gè)棧;
2、將字符串s轉(zhuǎn)換成字符數(shù)組,并循環(huán)遍歷;
3、如果字符為:"{、(、["中的一個(gè),則存入集合中;
4、如果字符為:"}、)、]"中的一個(gè),則取出集合中最后一個(gè)元素進(jìn)行比較;
5、如能匹配上,則刪除集合中最后一個(gè)元素,否則返回false;
6、最后判斷集合大小是否為0,如是則返回true。

三、代碼實(shí)現(xiàn)
public boolean isValid(String s) {
    if ("".equals(s)) {
        return true;
    } else {
        Map<Character, Character> parentheseMap = new HashMap<Character, Character>();
        parentheseMap.put(')', '(');
        parentheseMap.put(']', '[');
        parentheseMap.put('}', '{');        
        char[] sArr = s.toCharArray();
        List<Character> stackList = new ArrayList<Character>();
        for (int i = 0; i < sArr.length; i++) {
            if (sArr[i] == '(' || sArr[i] == '[' || sArr[i] == '{') {
                stackList.add(sArr[i]);
            } else {
                if (stackList.size() == 0) {
                    return false;
                } else {
                    char temp = stackList.get(stackList.size() - 1);
                    if (temp == parentheseMap.get(sArr[i])) {
                        stackList.remove(stackList.size() - 1);
                    } else {
                        return false;
                    }
                }
            }
        }
        return stackList.size() == 0 ? true : false;
    }
}

新聞標(biāo)題:ValidParentheses之Java實(shí)現(xiàn)
本文URL:http://www.muchs.cn/article40/iidiho.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供響應(yīng)式網(wǎng)站、App開(kāi)發(fā)、Google、小程序開(kāi)發(fā)電子商務(wù)、App設(shè)計(jì)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

外貿(mào)網(wǎng)站建設(shè)