1、題目描述
題目鏈接:http://www.lintcode.com/zh-cn/problem/rotate-string/
給定一個字符串和一個偏移量,根據偏移量旋轉字符串(從左向右旋轉)
2、難點分析
特殊情況:①字符串為""的情況②offset=0的情況③offset遠大於字符串長度的情況
前兩種情況,如果想到了直接return就好。第三種情況難以想到,想到的話也好處理,因為如果偏移量offset為字符串長度的整數倍,那么偏移之后的結果其實就是源字符串,所以真正的偏移量應該為offset%(字符串的長度)。
3、Java代碼
public class Solution { /** * @param str: an array of char * @param offset: an integer * @return: nothing */ //沒有考慮字符串為""的情況 //沒有考慮到offset遠大於字符串長度的情況,導致時間超時 public void rotateString(char[] str, int offset) { // write your code here char temp; if(offset==0) return; 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; } } }
樣例
對於字符串 "abcdefg"
.
offset=0 => "abcdefg"
offset=1 => "gabcdef"
offset=2 => "fgabcde"
offset=3 => "efgabcd"