精華區beta Marginalman 關於我們 聯絡資訊
1249. Minimum Remove to Make Valid Parentheses 有一個字串由小寫字母、左括號、右括號組成 左括號、右括號必須互相配對 請把所有不合法的括號拿掉 思路: 用一個stack紀錄所有左括號的位置 遇到左括號就把左括號丟到stack裡面 遇到右括號就看stack裡面有沒有東西 沒有就代表這個右括號是不合法的,把它拿掉 最後要在遍歷一次stack把裡面所有左括號拿掉 golang code func minRemoveToMakeValid(s string) string { stack := []int{} temp := []byte(s) i := 0 for i < len(temp) { if temp[i] == '(' { stack = append(stack, i) } else if temp[i] == ')' { if len(stack) > 0 { stack = stack[:len(stack)-1] } else { temp = append(temp[:i], temp[i+1:]...) i-- } } i++ } for i := len(stack) - 1; i > -1; i-- { temp = append(temp[:stack[i]], temp[stack[i]+1:]...) } return string(temp) } -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 111.82.26.211 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1712392789.A.54D.html
SecondRun: 大師 04/06 16:50
digua: 大師 04/06 16:51
SecondRun: golang要處理資料我都覺得好麻煩窩 04/06 17:00