二. 棧 1 有效的括號序列

問題:給定一個字符串所表示的括號序列,包含以下字符: '(', ')', '{', '}', '[' and ']', 判定是否是有效的括號序列
如括號必須依照 "()" 順序表示, "()[]{}" 是有效的括號,但 "([)]"則是無效的括號。

思路: 括號最重要的是匹配,只要出現()[]{},就可以抵消掉,否則就false,而且對于stack的第一個元素 不能是}]),其他的就可以push入棧。
這里,我們用數組來模擬stack,string作為輸入源。
注意匹配的順序,不能是“)(”。
Python3

class Solution:
    # @param {string} s A string
    # @return {boolean} whether the string is a valid parentheses
    def isValidParentheses(self, s):
        # Write your code here
        stack = []
        for index in s:
            if index == "(" or index == "{" or index == "[":
                stack.append(index)
                continue
            length = len(stack)
            if stack:
                if index == ")" and  stack[length - 1] == "(":
                    stack.pop()
                    continue
                if index == "}" and  stack[length - 1] == "{":
                    stack.pop()
                    continue
                if index == "]" and  stack[length - 1] == "[":
                    stack.pop()
                    continue
                else:
                    return False
            else:
                if index == "}" or index == "]" or index == ")":
                    return False

        if stack:
            return False
        else:
            return True

這里,我有遇到一個問題,如何判斷一個數組為空。
stack == None 是行不通的。
親測以下均可:

a = []
if not bool(a):

if not a:

if len(a) == 0:

if a == []:

也就是說,一個空的列表 == 0 == False

java

public class Solution {
    /**
     * @param s A string
     * @return whether the string is a valid parentheses
     */
    public boolean isValidParentheses(String s) {
        // Write your code here
        Stack<Character> stack = new Stack<Character>();
        for (char bracket: s.toCharArray())
        {
            if (bracket == '(')
            {
                stack.push(')');
            }
            else if (bracket == '{')
            {
                stack.push('}');
            }
            else if (bracket == '[')
            {
                stack.push (']');
            }
            else if (stack.isEmpty() || bracket != stack.pop())
            {
                return false;
            }
        }
        return stack.isEmpty();
    }
}

在用java做的時候,我發現了一個好方法,就是如上思路,簡潔可行。

也發現了幾個問題:

  1. java中 “{” 和 ‘{’ 是不一樣的類型:第一個是string 第二個是 char。
  2. java中有現成的stack,c++也有,反而就是python沒有。但是他們建立順序棧的方式都差不多,均用了數組。

下面就是相關的信息:
Java 數據結構包括: 枚舉(Enumeration)位集合(BitSet)向量(Vector)棧(Stack)字典(Dictionary)哈希表(Hashtable)屬性(Properties)

Python3數據結構包括:列表(棧,隊列)集合,字典,元組

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 1. Java基礎部分 基礎部分的順序:基本語法,類相關的語法,內部類的語法,繼承相關的語法,異常的語法,線程的語...
    子非魚_t_閱讀 31,778評論 18 399
  • //Clojure入門教程: Clojure – Functional Programming for the J...
    葡萄喃喃囈語閱讀 3,779評論 0 7
  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,993評論 19 139
  • 路人的故事,一點一點pick up and記錄。 有些人,現在不是路人,時間久了,也真的成了路人。加上人總在變,樣...
    去社閱讀 367評論 0 0
  • One洗手間里,我正在費力拉粑粑,隔壁傳來細細碎碎的嗚咽啜泣。哭聲低沉、壓抑、悲嘁、絕望。 Two有一天晚上,我正...
    我腦袋單細胞閱讀 540評論 0 0