LeetCode解題之六:有效的括號

題目

給定一個只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判斷字符串是否有效。

有效字符串需滿足:

左括號必須用相同類型的右括號閉合。
左括號必須以正確的順序閉合。
注意空字符串可被認爲是有效字符串。
示例 1:

輸入: "()"
輸出: true

示例 2:

輸入: "()[]{}"
輸出: true

示例 3:

輸入: "(]"
輸出: false

分析

本題不難,主要就是個配對的問題。首先將左括號壓入棧進行臨時存儲,再去判斷對應的右括號是否存在,如果不是成對出現則認爲不是有效字符串,如果是則認爲是有效字符串。

解答

 public static boolean isValid(String s) {
        if (StringUtils.isEmpty(s)) {
            return true;
        }
        Stack<Character> parenthesesStack = new Stack<>();
        for (Character c : s.toCharArray()) {
            if (c == '(' || c == '[' || c == '{') {
                parenthesesStack.push(c);
            }
            if (c == ')') {
                if (parenthesesStack.isEmpty() || parenthesesStack.pop() != '(') {
                    return false;
                }
            }
            if (c == ']') {
                if (parenthesesStack.isEmpty() || parenthesesStack.pop() != '[') {
                    return false;
                }
            }
            if (c == '}') {
                if (parenthesesStack.isEmpty() || parenthesesStack.pop() != '{') {
                    return false;
                }
            }
        }

        return parenthesesStack.isEmpty();

    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章