LeetCode筆記:20. Valid Parentheses

問題:

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

大意:

給出一個(gè)只包含 '(', ')', '{', '}', '[' 和 ']' 的字符串,判斷它的輸入是否是有效的。
括號(hào)必須是以正確的順序關(guān)閉的, "()" 和 "()[]{}" 都是有效的,但是 "(]" 和 "([)]" 是無效的。

思路:

題目的要求說來也簡單,就是判斷括號(hào)是不是有效的,自己先用測試用例試了一下,括號(hào)中包含括號(hào)也是有效的。

其實(shí)無效的情況也就幾種,左括號(hào)匹配到了不一樣的右括號(hào)、左括號(hào)多了、右括號(hào)多了,我用一個(gè)數(shù)組記錄不同位置出現(xiàn)的括號(hào)的種類,出現(xiàn)新的右括號(hào)的時(shí)候判斷是否匹配到了正確的括號(hào),還要看是不是是多了的右括號(hào),最后看有沒有多出來的左括號(hào)。方法很笨,代碼也寫的很冗余,不過速度還可以。

代碼(Java):

public class Solution {
    public boolean isValid(String s) {
        int[] markArr = new int[s.length()];// 1表示(),2表示[],3表示{}
        
        char[] arr = s.toCharArray();
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == '(') {
                markArr[i] = 1;
            } else if (arr[i] == ')') {
                boolean hasMatched = false;
                for (int j = i-1; j >= 0; j--) {
                    if (markArr[j] > 0 && markArr[j] != 1) return false;
                    else if (markArr[j] == 1) {
                        markArr[j] = 0;
                        hasMatched = true;
                        break;
                    }
                }
                if (!hasMatched) return false;
            } else if (arr[i] == '[') {
                markArr[i] = 2;
            } else if (arr[i] == ']') {
                boolean hasMatched = false;
                for (int j = i-1; j >= 0; j--) {
                    if (markArr[j] > 0 && markArr[j] != 2) return false;
                    else if (markArr[j] == 2) {
                        markArr[j] = 0;
                        hasMatched = true;
                        break;
                    }
                }
                if (!hasMatched) return false;
            } else if (arr[i] == '{') {
                markArr[i] = 3;
            } else if (arr[i] == '}') {
                boolean hasMatched = false;
                for (int j = i-1; j >= 0; j--) {
                    if (markArr[j] > 0 && markArr[j] != 3) return false;
                    else if (markArr[j] == 3) {
                        markArr[j] = 0;
                        hasMatched = true;
                        break;
                    }
                }
                if (!hasMatched) return false;
            }
        }
        
        for (int i = 0; i < markArr.length; i++) {
            if (markArr[i] > 0) return false;
        }
        return true;
    }
}

他山之石:

public class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<Character>();
        // Iterate through string until empty
        for(int i = 0; i<s.length(); i++) {
            // Push any open parentheses onto stack
            if(s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{')
                stack.push(s.charAt(i));
            // Check stack for corresponding closing parentheses, false if not valid
            else if(s.charAt(i) == ')' && !stack.empty() && stack.peek() == '(')
                stack.pop();
            else if(s.charAt(i) == ']' && !stack.empty() && stack.peek() == '[')
                stack.pop();
            else if(s.charAt(i) == '}' && !stack.empty() && stack.peek() == '{')
                stack.pop();
            else
                return false;
        }
        // return true if no open parentheses left in stack
        return stack.empty();
    }
}

這個(gè)做法用到了Stack棧這個(gè)類型,確實(shí)這道題很適合用棧來做,先進(jìn)后出,遇到左括號(hào)的時(shí)候放進(jìn)去,遇到右括號(hào)的時(shí)候從棧頂拿括號(hào)進(jìn)行匹配,匹配失敗就錯(cuò)了,全部匹配正確而且最后棧里沒東西了就對(duì)了。代碼簡潔多了。

合集:https://github.com/Cloudox/LeetCode-Record


查看作者首頁

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容