32.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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 longestValidParentheses(s string) int {
  24. stack := []int{}
  25. // max: longest length, beg: idx of last ')' before current stack
  26. max, beg := 0, -1
  27. for i := 0; i < len(s); i++ {
  28. if s[i] == '(' {
  29. stack = append(stack, i)
  30. } else if s[i] == ')' {
  31. if len(stack) > 0 {
  32. // pop last '('
  33. stack = stack[:len(stack)-1]
  34. } else {
  35. beg = i
  36. continue
  37. }
  38. if len(stack) == 0 {
  39. // curr idx is the end of curr seq
  40. max = maxInt(max, i-beg)
  41. } else {
  42. // top of stack is the beg of curr seq
  43. max = maxInt(max, i-stack[len(stack)-1])
  44. }
  45. }
  46. }
  47. return max
  48. }
  49. // func main() {
  50. // fmt.Println(longestValidParentheses("("))
  51. // fmt.Println(longestValidParentheses("()()("))
  52. // fmt.Println(longestValidParentheses("()(((()(()(((()(()())))(()"))
  53. // }