|
| 1 | +package com.codedifferently.lesson14; |
| 2 | + |
| 3 | +public class Lesson14 { |
| 4 | + |
| 5 | + public static void main(String[] args) { |
| 6 | + System.out.println("The permutations of 'abc' are:"); |
| 7 | + printPermutations("abc", ""); |
| 8 | + |
| 9 | + System.out.println(); |
| 10 | + System.out.print("The reverse of 'abcd' is: "); |
| 11 | + System.out.println(reverseString("abc")); |
| 12 | + } |
| 13 | + |
| 14 | + /** |
| 15 | + * Prints all the permutations of a string. |
| 16 | + * |
| 17 | + * @param value The string to permute. |
| 18 | + * @param answer The current permutation. |
| 19 | + */ |
| 20 | + public static void printPermutations(String value, String answer) { |
| 21 | + if (value.length() == 0) { |
| 22 | + System.out.println(answer); |
| 23 | + return; |
| 24 | + } |
| 25 | + |
| 26 | + for (int i = 0; i < value.length(); i++) { |
| 27 | + char ch = value.charAt(i); |
| 28 | + String left = value.substring(0, i); |
| 29 | + String right = value.substring(i + 1); |
| 30 | + String rest = left + right; |
| 31 | + printPermutations(rest, answer + ch); |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + /** |
| 36 | + * Reverses a string by swapping the front half of the characters with the back half. |
| 37 | + * |
| 38 | + * @param input The string to reverse. |
| 39 | + * @return The reversed string. |
| 40 | + */ |
| 41 | + public static String reverseString(String input) { |
| 42 | + if (input.length() == 0) { |
| 43 | + return input; |
| 44 | + } |
| 45 | + |
| 46 | + char[] charArray = input.toCharArray(); |
| 47 | + |
| 48 | + for (int i = 0; i < charArray.length / 2; i++) { |
| 49 | + // Compute the corresponding index from the back of the string. |
| 50 | + var j = charArray.length - i - 1; |
| 51 | + swapCharacters(charArray, i, j); |
| 52 | + } |
| 53 | + |
| 54 | + return new String(charArray); |
| 55 | + } |
| 56 | + |
| 57 | + /** |
| 58 | + * Swaps the characters in the provided character array. |
| 59 | + * |
| 60 | + * @param charArray |
| 61 | + * @param i |
| 62 | + * @param j |
| 63 | + */ |
| 64 | + private static void swapCharacters(char[] charArray, int i, int j) { |
| 65 | + Character temp = charArray[i]; |
| 66 | + charArray[i] = charArray[j]; |
| 67 | + charArray[j] = temp; |
| 68 | + } |
| 69 | +} |
0 commit comments