32.go 1.2 KB

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