Right shift a given string by n characters.
Assumptions
- The given string is not null.
- n >= 0.
Examples
- "abc", 4 -> "cab"
public class Solution { public String rightShift(String input, int n) { // Write your solution here if (input.length() == 0) { return input; } char[] charArr = input.toCharArray(); int len = n % charArr.length; // reverse in 3 steps, similar like reverse words in sentense reverse(charArr, 0, charArr.length - 1); reverse(charArr, 0, len - 1); reverse(charArr, len, charArr.length - 1); return new String(charArr); } private void reverse(char[] charArr, int start, int end) { while (start < end) { char tmp = charArr[start]; charArr[start] = charArr[end]; charArr[end] = tmp; start += 1; end -= 1; } } }