LintCode——旋转字符串

时间:2021-06-06 10:52:21

描述:给定一个字符串和一个偏移量,根据偏移量旋转字符串(从左向右旋转)

样例:对于字符串 "abcdefg" 

     offset=0 => "abcdefg"

     offset=1 => "gabcdef"

     offset=2 => "fgabcde"

     offset=3 => "efgabcd"

1、Python

 class Solution:
"""
@param str: An array of char
@param offset: An integer
@return: nothing
"""
def rotateString(self, str, offset):
# write your code here
if not offset: return #无偏移量
if not str: return #字符串是空串 offset = offset % len(str)
for i in range(offset): #字符串旋转
c = str.pop()
str.insert(0,c)
return str

2、Java

 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
char temp;
if(offset == 0) return; //偏移量为0
if(str.length == 0) return; //字符串为空串 int len=str.length;
for(int i = 1;i <= offset % len;i++){
temp = str[len - 1];
int j = len - 2;
while(j >= 0){
str[j + 1] = str[j];
j--;
}
str[0]=temp;
}
}
}