• 描述

字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请定义一个函数实现字符串左旋转操作的功能。比如,输入字符串"abcdefg"和数字2,该函数将返回左旋转两位得到的结果"cdefgab"。

 

  • 示例 1:

输入: s = "abcdefg", k = 2
输出: "cdefgab"

  • 示例 2:

输入: s = "lrloseumgh", k = 6
输出: "umghlrlose"
 

限制:

1 <= k < s.length <= 10000

  • Solution one

利用Java substring实现

class Solution {
    public String reverseLeftWords(String s, int n) {
        return new String(s.substring(n) + s.substring(0,n));
    }
}
  • Solution two

利用System.arraycopy实现

  • Arrays.copyOf
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
        T[] copy = ((Object)newType == (Object)Object[].class)
            ? (T[]) new Object[newLength]
            : (T[]) Array.newInstance(newType.getComponentType(), newLength);
        System.arraycopy(original, 0, copy, 0,
                         Math.min(original.length, newLength));
        return copy;
    }
  • System.arraycopy
public static native void arraycopy(Object src,  int  srcPos,
                                        Object dest, int destPos,
                                        int length);
class Solution {
    public String reverseLeftWords(String s, int n) {
        char [] res = new char[s.length()];
        char [] temp = s.toCharArray();
        System.arraycopy(temp,0,res,s.length() - n,n);
        System.arraycopy(temp,n,res,0,s.length() - n);
        return String.copyValueOf(res);
    }
}