385.mini-parser.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /**
  2. * // This is the interface that allows for creating nested lists.
  3. * // You should not implement it, or speculate about its implementation
  4. * type NestedInteger struct {
  5. * }
  6. *
  7. * // Return true if this NestedInteger holds a single integer, rather than a nested list.
  8. * func (n NestedInteger) IsInteger() bool {}
  9. *
  10. * // Return the single integer that this NestedInteger holds, if it holds a single integer
  11. * // The result is undefined if this NestedInteger holds a nested list
  12. * // So before calling this method, you should have a check
  13. * func (n NestedInteger) GetInteger() int {}
  14. *
  15. * // Set this NestedInteger to hold a single integer.
  16. * func (n *NestedInteger) SetInteger(value int) {}
  17. *
  18. * // Set this NestedInteger to hold a nested list and adds a nested integer to it.
  19. * func (n *NestedInteger) Add(elem NestedInteger) {}
  20. *
  21. * // Return the nested list that this NestedInteger holds, if it holds a nested list
  22. * // The list length is zero if this NestedInteger holds a single integer
  23. * // You can access NestedInteger's List element directly if you want to modify it
  24. * func (n NestedInteger) GetList() []*NestedInteger {}
  25. */
  26. func deserialize(s string) *NestedInteger {
  27. ni := &NestedInteger{}
  28. if s == "[]" {
  29. return ni
  30. }
  31. n := len(s)
  32. if s[0] != '[' {
  33. i, _ := strconv.Atoi(s)
  34. ni.SetInteger(i)
  35. return ni
  36. }
  37. prev, comma := 1, nextComma(s, 1, n-1)
  38. for comma != -1 {
  39. ni.Add(*deserialize(s[prev:comma]))
  40. prev = comma + 1
  41. comma = nextComma(s, prev, n-1)
  42. }
  43. ni.Add(*deserialize(s[prev : n-1]))
  44. return ni
  45. }
  46. func nextComma(s string, beg, end int) int {
  47. for cnt, i := 0, beg; i < end; i++ {
  48. if s[i] == '[' {
  49. cnt++
  50. } else if s[i] == ']' {
  51. cnt--
  52. }
  53. if cnt == 0 && s[i] == ',' {
  54. return i
  55. }
  56. }
  57. return -1
  58. }