(s string, k int)
| 3 | import "math" |
| 4 | |
| 5 | func 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. |
no outgoing calls