8. 旋转字符串

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/xwdrhgr/article/details/102738191

给定一个字符串(以字符数组的形式给出)和一个偏移量,根据偏移量原地旋转字符串(从左向右旋转)。

样例

样例 1:

输入: str="abcdefg", offset = 3

输出: str = "efgabcd"

样例解释: 注意是原地旋转,即str旋转后为"efgabcd"

样例 2:

输入: str="abcdefg", offset = 0

输出: str = "abcdefg"

样例解释: 注意是原地旋转,即str旋转后为"abcdefg"

样例 3:

输入: str="abcdefg", offset = 1

输出: str = "gabcdef"

样例解释: 注意是原地旋转,即str旋转后为"gabcdef"

样例 4:

输入: str="abcdefg", offset =2

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

猜你喜欢

转载自blog.csdn.net/xwdrhgr/article/details/102738191