题目 “Rotate String”
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.
题目详解
题目的要求是输入一个字符串str,与int型数据offset,对str做offset次依次向右移动。
只需要获得str的长度length,对offset求length的余数,相当于仅作length次变换即可。因为对字符串变换length次数的整数倍相当于还是原来的字符串,并没有发生变化。
源码
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
if(!str.empty()) //判断是否为空字符串,若为空,则不需要变换,直接退出
{
int real_offset;
real_offset=offset%str.length(); //offset先对str的长度求余,该余数即为需要转动的次数
for(int i=0;i<real_offset;i++)
{
string get="";
string str_copy=str; //设原str=abcdefg
get=str_copy[str_copy.length()-1]; //获取str_copy的最后一个字符g,则get="g"
str_copy.erase(str_copy.length()-1); //删除str_copy的最后一个字符g,str_copy=abcdef
str=get+str_copy; //将get放在str_copy前面进行连接
}
}
}
};