MCPcopy Create free account
hub / github.com/austingebauer/go-leetcode / reverseStr

Function reverseStr

reverse_string_ii_541/solution.go:5–25  ·  view source on GitHub ↗
(s string, k int)

Source from the content-addressed store, hash-verified

3import "math"
4
5func reverseStr(s string, k int) string {
6 r := []rune(s)
7 for i := 0; i < len(s); i += 2 * k {
8 // get the index to the end of k chars starting at i
9 // pick the minimum for the case where the next k
10 // characters falls off the end of s.
11 j := int(math.Min(float64(i+k-1), float64(len(s)-1)))
12
13 // reverse the string in the range of [i, j]
14 s := i
15 for s < j {
16 hold := r[s]
17 r[s] = r[j]
18 r[j] = hold
19 s++
20 j--
21 }
22 }
23
24 return string(r)
25}
26
27// Note: original solution from mock interview.
28// I learned how to reverse string in place by using []rune or []byte.

Callers 1

Test_reverseStrFunction · 0.85

Calls

no outgoing calls

Tested by 1

Test_reverseStrFunction · 0.68