给定一个字符串和一个偏移量,根据偏移量旋转字符串(从左向右旋转)
样例
对于字符串 “abcdefg”.
offset=0 => “abcdefg”
offset=1 => “gabcdef”
offset=2 => “fgabcde”
offset=3 => “efgabcd”
挑战
在数组上原地旋转,使用O(1)的额外空间
思路:
①新创建一个字符串数组suffix,依次存放倒数的offset个数;
②将原字符串数组str中的元素,依次向后移动offset个位置
③suffix中存放的元素,全部转移到str的前offset个位置
需要注意:如果offset>str的长度,要对offset取模;
off = offset%str.size()
C++:
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())
return;
int off = offset%str.size();
if(off!=0)
{
string suffix(off+1,'\0');
int i,j,size = str.size();
for(j=0,i=size-off;i<size;i++,j++)
{
suffix[j] = str[i];
}
for(i=size-off-1;i>=0;i--)
{
str[i+off] = str[i];
}
for(i=0;i<off;i++)
{
str[i] = suffix[i];
}
}
}
};
Py3:
pothon 中 的 for i in range(4,6) 指的是4,5 即4<=i<6
容易出错
class Solution:
"""
@param str: An array of char
@param offset: An integer
@return: nothing
"""
def rotateString(self, str, offset):
# write your code here
size = len(str)
if size == 0:
return
off = offset%size
if off == 0:
return
if off!=0:
suffix = []
for i in range(size-off,size):
# TODO: write code...
suffix.append(str[i])
j = size-off-1
while j>=0:
str[j+off] = str[j]
j -= 1
for k in range(0,off):
str[k] = suffix[k]