Question (in Chinese): http://ac.jobdu.com/problem.php?pid=1362
Question Name: Left Rotate String
Question Description: given a string, rotate it leftward by some length.
Input: the input might contain multiple test cases. Each line, as a test case, contains a string and a non-negative integer.
Output: print the reversed string.
1 2 3 4 5 6 | Input: UDBOJ 4 abba 1 Output: JUDBO bbaa |
This question is quite similar with the previous one. So is the solution. The solution is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | /*---------------------------------------------------------------- * Author: Sheng Yu - codesays.com * Written: 09/09/2014 * Last updated: 09/09/2014 * * Filename: LeftRotateString.java * Compilation: javac LeftRotateString.java * Execution: java LeftRotateString * JDK Used: 1.7 *----------------------------------------------------------------*/ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.StreamTokenizer; /** * The utility to rotate a string. * @author Sheng Yu codesays.com */ public class LeftRotateString { /** * Reverse the input[begin : end], both index inclusive. * @param input the char array to reverse. * @param begin the begin position of the to-reverse sub-array. * @param end the end position of the to-reverse sub-array. */ private static void reverseArray(char[] input, int begin, int end) { int beginPos = begin, endPos = end; char temp; while (beginPos < endPos) { temp = input[beginPos]; input[beginPos++] = input[endPos]; input[endPos--] = temp; } return; } /** * Left rotate the string by rotateLen characters. * @param origin the original string to rotate. * @param rotateLen the left rotate length. * @return the rotated string. */ public static String leftRotate(String origin, int rotateLen) { char[] inputChars = origin.toCharArray(); int rotate = rotateLen % origin.length(); // Rotate the two parts individually. reverseArray(inputChars, 0, rotate - 1); reverseArray(inputChars, rotate, origin.length()-1); // Rotate the whole string. reverseArray(inputChars, 0, origin.length()-1); return new String(inputChars); } /** * Stub for test. * @param args the command line arguments. * @throws IOException when input gets error. */ public static void main(String[] args) throws IOException { StreamTokenizer st = new StreamTokenizer(new BufferedReader( new InputStreamReader(System.in))); String input = null; int rotateLen = 0; while (st.nextToken() != StreamTokenizer.TT_EOF) { input = st.sval; st.nextToken(); rotateLen = (int) st.nval; System.out.println(leftRotate(input, rotateLen)); } } } |