Right Shift By N Characters

Solution: 三步翻转法

  public String rightShift(String input, int n) {
    // Write your solution here.
    if (input == null || input.length() < 2 || n <= 0) {
      return input;
    }
    char[] chars = input.toCharArray();
    n %= input.length();
    reverse(chars, 0, chars.length - 1 - n);
    reverse(chars, chars.length - n, chars.length - 1);
    reverse(chars, 0, chars.length - 1);
    return new String(chars);
  }
  private void reverse(char[] chars, int i, int j) {
    while (i < j) {
      char temp = chars[i];
      chars[i] = chars[j];
      chars[j] = temp;
      i++;
      j--;
    }
  }

results matching ""

    No results matching ""