424.longest-repeating-character-replacement.go 766 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. type SegmentTree struct {
  2. tree []int
  3. size int
  4. }
  5. func newST(n int) SegmentTree {
  6. return SegmentTree{
  7. tree: make([]int, 2*n),
  8. size: n,
  9. }
  10. }
  11. func (st SegmentTree) add(i, val int) {
  12. i += st.size
  13. st.tree[i] += val
  14. for 1 < i {
  15. j := i / 2
  16. st.tree[j] = maxInt(st.tree[2*j], st.tree[2*j+1])
  17. i = j
  18. }
  19. }
  20. func maxInt(x, y int) int {
  21. if x < y {
  22. return y
  23. }
  24. return x
  25. }
  26. func characterReplacement(s string, k int) (max int) {
  27. n := len(s)
  28. if n-1 <= k {
  29. return n
  30. }
  31. bytes := []byte(s)
  32. st := newST(26)
  33. fast, slow, cnt := 0, 0, 0
  34. for ; fast < n; fast++ {
  35. st.add(int(bytes[fast]-'A'), 1)
  36. cnt = st.tree[1]
  37. for cnt+k < fast-slow+1 {
  38. st.add(int(bytes[slow]-'A'), -1)
  39. slow++
  40. cnt = st.tree[1]
  41. }
  42. max = maxInt(max, fast-slow+1)
  43. }
  44. return
  45. }