旋转字符转

给定一个字符串和一个偏移量,根据偏移量旋转字符串(从左往右旋转),要求在数组上原地旋转,空间复杂度O(1)

static void reverse(char[] str,int offset) {
    int len = str.Length;
    if (len == 0) return;

    char temp = str[0];
    char temp2 = str[0];
    int curent = 0;
    int target = 0;
    int start = 0;
    for (int i = 0; i < len; i++)
    {
        target = (curent + offset) % len;
        temp2 = str[target];//将原来的值弹出来保存
        str[target] = temp;//替换到目标位置为上次弹出来的值
        temp = temp2;//保存起来
        curent = target;

        if (start == target)
        {
            //如果目标的值是原来起始的位置,当前位置是旋转过的,那就往下走一步
            start = (start + 1) % len;
            curent = start;
            temp = str[curent];
        }
    }
}


看注释。


首页 我的博客
粤ICP备17103704号