ABSubStr.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package main
  2. func main() {
  3. println(getAns("ABAAABBBA"))
  4. println(getAns("ABAAAABBBA"))
  5. println(getAns("ABAAAAABBBA"))
  6. println(getAns("AAAAAA"))
  7. println(getAns("BABAABBABABABAAABAABABABBBAAABBAAABAABBBABBAAABABBBBBBBBBBBBAABBBBAAABAAAAABBBBBABBABBAABABAAABBABAABBAAAABBAABBBABABABABABBBAAABBBABAABAAAABBBBBAABBBABBBBAAABBABBAAABBABBABBBBBBBBBBBBBAABBAAAABAABABAABBBABBAAAAAABAABAABABBABAABBAAABBBBAABABBBABABAABAAABABBBBAABBAAABBBBBBABBAABAABABBBBBBBABBAAAABBABABBBBBBABABAABBABAABABBBBABBABBAABBAABBABABABBBAABBAABAABAABBBBBBBBBABAAABBAAAABBBAABABABBABAAAABABBABBAABAAABBBBBBAABABAAABAAABBABAABAABAAAABABAABABABAABABAAABBBBBAAAAAABAABBBABBBABBBBBBAAABABAAAABABAAAAAABABAABABBBABAAAAABAABBBAABBBAAAABAAAAABBBABABABBBAABAAAAAABABBBABABBBABBABABBBBABABBABABBBABABBAAAABAABBBAABABABABABAAABAABBAAAABAAAAABAABBBBABABBBBAABAABBBBABBAAAAAAAAAABBBAAABAAABBAAAAAAABBAAAAAABAAABBAABABABABBAAAAAABABAAABABABBBABAABBBABAABBAAAABBBBAAAABBAAAAABABBBABBAAABABABBAABABAABBBBAABAAABAABBAAAAAABAAABBBAAAABBABABAABABAAABBAABBABABBBAABBABBAABABABAAABABBAABBABABABBABBBABAAAAAABBAABBBAAABAAABAAABBBBBABBABBBABBBAABBABAAAAABBABABBABAAAAAABBBABABBABAABABAABBAAAAABABBAAABABABABBBAABB"))
  8. }
  9. func getAns(S string) int {
  10. length := len(S)
  11. sum := 0
  12. sumArr := make([]int, length)
  13. posMap := make(map[int]int)
  14. for i := 0; i < length; i++ {
  15. if S[i] == 'A' {
  16. sum++
  17. } else {
  18. sum--
  19. }
  20. sumArr[i] = sum
  21. posMap[sum] = i
  22. }
  23. if sum == 0 {
  24. return length
  25. } else if sum == length || sum == -length {
  26. return 0
  27. }
  28. maxLen := 0
  29. for i := 0; i < length; i++ {
  30. if sumArr[i] != 0 && maxLen < posMap[sumArr[i]]-i {
  31. maxLen = posMap[sumArr[i]] - i
  32. }
  33. }
  34. if posMap[0] != posMap[len(posMap)-1] && posMap[0]+1 > maxLen {
  35. maxLen = posMap[0] + 1
  36. }
  37. return maxLen
  38. }