Skip to content

Instantly share code, notes, and snippets.

@drem-darios
Last active June 23, 2020 05:16
Show Gist options
  • Select an option

  • Save drem-darios/a226f7e7511a5e2e2218bcfe30a2ecc3 to your computer and use it in GitHub Desktop.

Select an option

Save drem-darios/a226f7e7511a5e2e2218bcfe30a2ecc3 to your computer and use it in GitHub Desktop.
Rotates a String at the given index
import java.io.*;
import java.util.*;
/*
* Given an input String and an integer index, rotate the string around the given index
*/
public class RotateString {
public static void main(String[] args) {
String input = "123456";
System.out.println("Original: " + input);
String result = rotate(input, 3);
System.out.println("Result: " + result);
}
public static String rotate(String input, int pivot) {
char[] inputChars = input.toCharArray();
reverse(inputChars, 0, pivot-1);
// System.out.println(inputChars);
reverse(inputChars, pivot, input.length() - 1);
// System.out.println(inputChars);
reverse(inputChars, 0, input.length() - 1);
return new String(inputChars);
}
private static void reverse(char[] inputChars, int start, int end) {
int mid = (start + end)/2;
for (int i = start; i <= mid; i++) {
swap(inputChars, i, (start+end)-i);
}
}
private static void swap(char[] inputChar, int i, int j) {
char temp = inputChar[i];
inputChar[i] = inputChar[j];
inputChar[j] = temp;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment