**
Lintcode 008 :旋转字符串
**
题干描述:
给定一个字符串和一个偏移量,根据偏移量旋转字符串(从左向右旋转)
样例:
对于字符串 “abcdefg”.
offset=0 => “abcdefg”
offset=1 => “gabcdef”
offset=2 => “fgabcde”
offset=3 => “efgabcd”
分析:
我们思考可以发现给的offset数值过大的话如果一直循环会导致时间过长。
其实有效循环次数仅限于字符串长度,我们可以将offset除以字符串的商来得到有效循环次数,大大减少循环时间。
并且需要考虑到数组的空集情况。
public class Solution {
public void rotateString(char[] str, int offset) {
// write your code here
char temp;
int count = 0;
int length =0 ;
while(***str!= null && str.length>=1 && count < (offset%str.length)***)
{
int i = 0;
i = str.length-1;
temp = str[i];
for(int j = i;j>0;j--)
{
str[j] = str[j-1];
}
str[0]=temp;
count++;
}
}
}