美文网首页
Rotate String by Left

Rotate String by Left

作者: Star_C | 来源:发表于2018-04-16 23:06 被阅读0次

    Questions

    Hackerank
    Rotate a string of n characters by k steps.

    Idea

    Index Addition

    A position + X steps has a total length of X + 1

    Circular Moves

    Using % length to retrieve actual steps without meaningless step repetition

    Backward Move

    Think of a circle.
    Array.length is conceptually the same position as index 0. If you move left from position 0, you are actually moving left from position Array.length.

        public static void rotate(int[] a, int K) {
            int[] tmp = new int[a.length];
            int target = 0;
            int k = K % a.length;
            for(int i = 0; i < a.length; i++) {
                target = i < k?
                          a.length - (k - i):
                          i - k;
                tmp[target] = a[i];
            }
            for(int i = 0; i < a.length; i++) {
                a[i] = tmp[i];
            }
        }
    

    相关文章

      网友评论

          本文标题:Rotate String by Left

          本文链接:https://www.haomeiwen.com/subject/vduykftx.html