32.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package main
  2. // 穷举
  3. func longestValidParenthesesOld(s string) int {
  4. pair := 0
  5. for i := 0; i < len(s); i++ {
  6. left, right := 0, 0
  7. for j := i; j < len(s); j++ {
  8. if s[j] == '(' {
  9. left++
  10. } else {
  11. right++
  12. }
  13. if right > left {
  14. break
  15. }
  16. if left == right && left > pair {
  17. pair = left
  18. }
  19. }
  20. }
  21. return pair * 2
  22. }
  23. func maxInt(x, y int) int {
  24. if x > y {
  25. return x
  26. }
  27. return y
  28. }
  29. func longestValidParentheses(s string) int {
  30. stack := []int{}
  31. // max: longest length, beg: idx of last ')' before current stack
  32. max, beg := 0, -1
  33. for i := 0; i < len(s); i++ {
  34. if s[i] == '(' {
  35. stack = append(stack, i)
  36. } else if s[i] == ')' {
  37. if len(stack) > 0 {
  38. // pop last '('
  39. stack = stack[:len(stack)-1]
  40. } else {
  41. beg = i
  42. continue
  43. }
  44. if len(stack) == 0 {
  45. // curr idx is the end of curr seq
  46. max = maxInt(max, i-beg)
  47. } else {
  48. // top of stack is the beg of curr seq
  49. max = maxInt(max, i-stack[len(stack)-1])
  50. }
  51. }
  52. }
  53. return max
  54. }
  55. // func main() {
  56. // fmt.Println(longestValidParentheses("("))
  57. // fmt.Println(longestValidParentheses("()()("))
  58. // fmt.Println(longestValidParentheses("()(((()(()(((()(()())))(()"))
  59. // }