Shift String by K Chunks
Write a function reorderString(s, k) that takes a string s and an integer k as input. The function should reorder the string s by reversing every consecutive block of k characters. If the number of remaining characters in the string is less than k, those characters should also be reversed. The function should return the reordered string.
For example:
If s = "abcdefg" and k = 2:
- The first block is "ab", reverse it to "ba".
- The second block is "cd", reverse it to "dc".
- The third block is "ef", reverse it to "fe".
- The remaining block is "g" (less than
k), reverse it to "g". - Concatenating these gives "badcfeg".
If s = "abcdefg" and k = 3:
- The first block is "abc", reverse it to "cba".
- The second block is "def", reverse it to "fed".
- The remaining block is "g" (less than
k), reverse it to "g". - Concatenating these gives "cbafedg".
[ "abcdefg", "2" ]
Explanation. Original string: "abcdefg", k = 2. Chunks: "ab" -> "ba", "cd" -> "dc", "ef" -> "fe", "g" -> "g". Result: "badcfeg".
[ "abcdefg", "3" ]
Explanation. Original string: "abcdefg", k = 3. Chunks: "abc" -> "cba", "def" -> "fed", "g" -> "g". Result: "cbafedg".
[ "abcdefgh", "4" ]
Explanation. Original string: "abcdefgh", k = 4. Chunks: "abcd" -> "dcba", "efgh" -> "hgfe". Result: "dcbahgfe".
[ "abcde", "5" ]
Explanation. Original string: "abcde", k = 5. Only one chunk: "abcde" -> "edcba". Result: "edcba".
[ "abcde", "1" ]
Explanation. Original string: "abcde", k = 1. Each character is a chunk and reversing a single character changes nothing. Result: "abcde".
[ "a", "1" ]
Explanation. Original string: "a", k = 1. One chunk "a" -> "a". Result: "a".
[ "short", "10" ]
Explanation. Original string: "short", k = 10. k is greater than the string length. The entire string "short" is treated as one block and reversed to "trohs". Result: "trohs".
[ "programming", "4" ]
Explanation. Original string: "programming", k = 4. Chunks: "prog" -> "gorp", "ramm" -> "mmar", "ing" -> "gni". Result: "gorp mmargni".
Follow-up: Can you solve this problem in-place if the string `s` was represented as a mutable character array?
- `1 <= s.length <= 1000` - `1 <= k` - `s` consists only of lowercase English letters.
- Views
- 3