main.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package main
  2. import "fmt"
  3. func main() {
  4. fmt.Println(isValid2("(())}[]"))
  5. fmt.Println(isValid("()[]"))
  6. }
  7. func isValid(s string) bool {
  8. // (:40 [:91 {:123 ):41 ]:93 }:125
  9. length := len(s)
  10. if length == 0 {
  11. return true
  12. }
  13. // if length%2 == 1 {
  14. // return false
  15. // }
  16. stock := []int{}
  17. for i := 0; i < length; i++ {
  18. tmp := s[i]
  19. if tmp == 40 || tmp == 123 || tmp == 91 {
  20. stock = append(stock, int(tmp))
  21. } else if tmp == 41 {
  22. if len(stock) == 0 {
  23. return false
  24. }
  25. if stock[len(stock)-1] == 40 {
  26. stock = stock[:len(stock)-1]
  27. } else {
  28. stock = append(stock, int(tmp))
  29. }
  30. } else if tmp == 93 {
  31. if len(stock) == 0 {
  32. return false
  33. }
  34. if stock[len(stock)-1] == 91 {
  35. stock = stock[:len(stock)-1]
  36. } else {
  37. stock = append(stock, int(tmp))
  38. }
  39. } else if tmp == 125 {
  40. if len(stock) == 0 {
  41. return false
  42. }
  43. if stock[len(stock)-1] == 123 {
  44. stock = stock[:len(stock)-1]
  45. } else {
  46. stock = append(stock, int(tmp))
  47. }
  48. }
  49. }
  50. return len(stock) == 0
  51. }
  52. func isValid2(s string) bool {
  53. // (:40 [:91 {:123 ):41 ]:93 }:125
  54. length := len(s)
  55. if length == 0 {
  56. return true
  57. }
  58. mapdata := make(map[int]int)
  59. mapdata[40] = 41
  60. mapdata[91] = 93
  61. mapdata[123] = 125
  62. stock := []int{}
  63. for i := 0; i < length; i++ {
  64. tmp := s[i]
  65. if tmp == 40 || tmp == 123 || tmp == 91 {
  66. stock = append(stock, int(tmp))
  67. } else {
  68. if len(stock) == 0 {
  69. return false
  70. } else if mapdata[stock[len(stock)-1]] == int(tmp) {
  71. stock = stock[:len(stock)-1]
  72. } else {
  73. stock = append(stock, int(tmp))
  74. }
  75. }
  76. }
  77. return len(stock) == 0
  78. }