LintCode-8.旋转字符串

题目

描述

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

样例

对于字符串 "abcdefg".

offset=0 => "abcdefg"
offset=1 => "gabcdef"
offset=2 => "fgabcde"
offset=3 => "efgabcd"

解答

思路

乍一看的思路是建立新的数组往里面填,空间复杂度O(n),时间复杂度O(1)。看了一下“挑战“是空间复杂度O(1),那么就是循环咯(没百度,可能有更6的办法)。

按照字面意思往后偏移。offset是多少偏移多少次。
注意时间限制(Time Limit Exceed):offset = offset % length。

代码

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(str.length == 0) return;
        if(offset == 0) return;
        if(str.length < offset) offset = offset % str.length;
        while(offset>0){
            temp = str[str.length-1];
            for(int i = str.length - 1; i > 0;i--){
                str[i] = str[i-1];
            }
            str[0]=temp;
            offset--;
        }
    }
}

你可能感兴趣的:(LintCode-8.旋转字符串)