Last active
June 23, 2020 05:16
-
-
Save drem-darios/a226f7e7511a5e2e2218bcfe30a2ecc3 to your computer and use it in GitHub Desktop.
Rotates a String at the given index
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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