Go語言實現Valid Parentheses

2021-09-29 07:52:03 字數 1467 閱讀 9403

write a function called that takes a string of parentheses, and determines if the order of the parentheses is valid. the function should return true if the string is valid, and false if it』s invalid.

examples

「()」 => true

「)(()))」 => false

「(」 => false

「(())((()())())」 => true

方法1:

我們可以對』(『計數,遍歷字串,遇到』(『就遞增,遇到』)『遞減。如果在每次遍歷過程中,發現計數小於0,說明』)『數目超過了之前的』(『數目,該』)『已不存在配對的』(』,直接判斷非法。遍歷完成後,如果計數器大於0,說明有多餘的』(『沒有配對,判斷非法,否則合法。

方法2:

利用正規表示式解析器。如果所有圓括號配對,該pattern是可以正確解析的,否則我們可以認為非法。

方法3:

不斷將字串中的"()「刪除,直到字串中再沒有」()",此時,如果字串為空,則說明全部配對,否則說明有未配對的圓括號存在。

方法4:

利用輔助棧。遍歷字串,如果遇到』(』,則壓棧;遇到』)』,如果輔助棧非空,則執行一次出棧(棧內必定都是』(』),如果輔助棧為空,遇到無法匹配的』)』,認定非法。遍歷完成後,如果輔助棧不為空,則非法,否則合法。

方法1:

func

validparentheses

(parens string

)bool

else

}return c ==0}

}

方法2:

import

"regexp"

func

validparentheses

(parens string

)bool

方法3:

import

"strings"

func

validparentheses

(parens string

)bool

return parens ==

""}

方法4:

func

validparentheses

(parens string

)bool

}return s ==

""}

go語言實現鍊錶

宣告結構體 宣告全域性變數,儲存頭結點 var head node var curr node 宣告節點型別 type node struct 建立頭結點 func createheadnode data string node 新增新節點 func addnode data string node...

Go語言實現走迷宮

package main import fmt os exec os time 定義全域性變數 var 定義變數儲存r當前位置 currentrow 1 currentcol 1 定義變數儲存迷宮出口位置 索引 endrow 1 endcol 5 func main 2.定義乙個函式列印地圖 pri...

Go語言實現ping命令

ping是使用icmp協議 icmp協議的組成 type 8bits code 8bits 校驗碼 checksum,8bits id 16bits 序號 sequence,16bits 資料 這些組成部分的含義 1 type icmp的型別,標識生成的錯誤報文 2 code 進一步劃分icmp的型...