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.
题目模板
class Solution { public: /** * @param str: An array of char * @param offset: An integer * @return: nothing */ void rotateString(string &str, int offset) { // write your code here } };
题目大意
给你一个string类型的字符换和一个整形n,让你把这个字符串后面的n个字符弄到前面去,看题目上面给的例子会很轻松理解。
大概思路
要求O(1)的额外空间,就有点麻烦,但是不难,考察细节的一道题。不限定额外空间的话用strcat(),再拼接字符串会简单超多。
class Solution { public: /** * @param str: An array of char * @param offset: An integer * @return: nothing */ void rotateString(string &str, int offset) { // write your code here char c, c1; int len = str.length(); if(!len) return ; offset %= len; for(int i=0; i<offset; i++){ c = str[len-offset+i]; for(int j=len-offset-1+i; j>=i; j--){ c1 = str[j]; str[j+1] = c1; } str[i] = c; } } };
细节方面
他测试数据里面会有超过str.length()大小的offset,注意取余。
并且还测试了空值,既空str,要注意判断,为空的话直接return就可以了
题目链接:https://www.lintcode.com/problem/rotate-string/description