Note: original solution from mock interview. I learned how to reverse string in place by using []rune or []byte. Having to reverse by string concatenation make this problem tough. Also, the problem description was vague in cases with characters remaining to sort.
(s string, k int)
| 30 | // Also, the problem description was vague in cases with characters |
| 31 | // remaining to sort. |
| 32 | func reverseStrOrig(s string, k int) string { |
| 33 | if len(s) < k { |
| 34 | return s |
| 35 | } |
| 36 | |
| 37 | i := 0 |
| 38 | for i+k < len(s) { |
| 39 | end := i + k |
| 40 | j := end - 1 |
| 41 | revStr := "" |
| 42 | for j >= i { |
| 43 | revStr += string(s[j]) |
| 44 | j-- |
| 45 | } |
| 46 | |
| 47 | s = s[0:i] + revStr + s[end:] |
| 48 | i = i + (2 * k) |
| 49 | |
| 50 | // if there are less than k characters left, reverse all of them |
| 51 | charsLeft := len(s) - end |
| 52 | if charsLeft < k { |
| 53 | // reverse all of them |
| 54 | e := len(s) - 1 |
| 55 | revStr := "" |
| 56 | for e >= end { |
| 57 | revStr += string(s[e]) |
| 58 | e-- |
| 59 | } |
| 60 | |
| 61 | s = s[0:end] + revStr |
| 62 | } |
| 63 | |
| 64 | // if there are less than 2k but greater than or equal to k characters, |
| 65 | // then reverse the first k characters and left the other as original |
| 66 | if charsLeft < 2*k && charsLeft > k { |
| 67 | // reverse the first k characters |
| 68 | h := end + k |
| 69 | e := h - 1 |
| 70 | revStr := "" |
| 71 | for e >= end { |
| 72 | revStr += string(s[e]) |
| 73 | e-- |
| 74 | } |
| 75 | |
| 76 | s = s[0:end] + revStr + s[h:] |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | return s |
| 81 | } |
nothing calls this directly
no outgoing calls
no test coverage detected