Rotate String
Problem:
感觉这道题应该归为medium, 自己想肯定想不出来。
Take offset = 2 as an example. Reverse abcde first, then reverse fg, reverse the whole string at last.
Step 1: edcbafg
Step 2: edcbagf
Step 3: fgabcde
Solution:
Offset > str.length has take into consideration. Pre process offset by offset%str.length.
Given a string and an offset, rotate string by offset. (rotate from left to right)
Example
Analysis:
Given
"abcdefg"
.offset=0 => "abcdefg"
offset=1 => "gabcdef"
offset=2 => "fgabcde"
offset=3 => "efgabcd"
感觉这道题应该归为medium, 自己想肯定想不出来。
Take offset = 2 as an example. Reverse abcde first, then reverse fg, reverse the whole string at last.
Step 1: edcbafg
Step 2: edcbagf
Step 3: fgabcde
Solution:
Offset > str.length has take into consideration. Pre process offset by offset%str.length.
public class Solution { /** * @param str: An array of char * @param offset: An integer * @return: nothing */ public void rotateString(char[] str, int offset) { // write your code here if (str == null || str.length == 0) return; offset = offset % str.length; reverse(str, 0, str.length - offset - 1); reverse(str, str.length - offset, str.length - 1); reverse(str, 0, str.length - 1); } private void reverse(char[] str, int start, int end) { while (start < end) { char temp = str[start]; str[start] = str[end]; str[end] = temp; start++; end--; } } }
评论
发表评论