[Algorithm] 8. Rotate String

Description

Given a string and an offset, rotate string by offset. (rotate from left to right)

Example

Given "abcdefg".

offset=0 => "abcdefg"
offset=1 => "gabcdef"
offset=2 => "fgabcde"
offset=3 => "efgabcd"

Challenge

Rotate in-place with O(1) extra memory.

Solution

 1     /**
 2      * @param str: An array of char
 3      * @param offset: An integer
 4      * @return: nothing
 5      */
 6     void reverseString(string &str, int start, int end)
 7     {
 8         int swap = 0;
 9         
10         while(start < end){
11             // Exchange the element between the start and the end.
12             swap = str[start];
13             str[start] = str[end];
14             str[end] = swap;
15             
16             // Move to the next index.
17             start++; end--;
18         }
19         
20         return ;
21     }
22      
23     void rotateString(string &str, int offset) {
24         // Get the length of the string.
25         int len = str.length();
26         if( !len || offset <= 0)    return ;
27         if( offset > len )  offset %= len;
28         
29         // Reverse the first section.
30         reverseString(str, 0, len-offset-1);
31         // Reverse the second section.
32         reverseString(str, len-offset, len-1);
33         // Reverse the entire section.
34         reverseString(str, 0, len-1);
35         
36         return ;
37     }

 

 

 

 

posted @ 2018-12-07 17:08  jjlovezz  阅读(225)  评论(0)    收藏  举报