Last active
February 21, 2026 19:04
-
-
Save youssef3wi/8e010ea06c50b3755db22c64b45bc1d2 to your computer and use it in GitHub Desktop.
Write a program to "factorize" the extremities of two ASCII strings `str1` and `str2`.
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
| /** | |
| * Write a program to "factorize" the extremities of two ASCII strings {@code str1} and {@code str2}. | |
| * <p> | |
| * Your must return a single string, initially made from the concatenation of two given strings. | |
| * The longest substrings that is common between the end of the first string and the beginning | |
| * of the second one must be factorized (written only once). | |
| * <p> | |
| * You must decide the concatenation order {@code str1 + str2} or {@code str2 + str1} so that | |
| * you get the best factorization. | |
| * <p> | |
| * When the same number characters can be factorized by the two concatenation | |
| * orders, prioritize {@code str1 + str2}. | |
| * <p> | |
| * <h3>Detailed example</h3> | |
| * With these parameters: | |
| * <ul> | |
| * <li>{@code str1 = "1234yyabc"}</li> | |
| * <li>{@code str2 = "abcxxxx1234"}</li> | |
| * </ul> | |
| * If you choose the order {@code str1 + str2} you could factorize the substring {@code "abc"}. Then, | |
| * you would return {@code "abcxxxx1234yyabc"}. | |
| */ | |
| public class Factorize { | |
| public static int redundant(String first, String second) { | |
| for (int idx = second.length() - 1; idx >= 0; idx--) { | |
| String sub = second.substring(0, idx); | |
| if (first.endsWith(sub)) { | |
| return sub.length(); | |
| } | |
| } | |
| return 0; | |
| } | |
| /** | |
| * @param str1 The first ASCII string to factorize. | |
| * @param str2 The second ASCII string to factorize. | |
| * @return The result string, after concatenation and factorization. | |
| */ | |
| public static String factorizeExtremities(String str1, String str2) { | |
| if (str1.equals(str2)) { | |
| return str1; | |
| } | |
| int firstOcc = redundant(str1, str2); | |
| int secondOcc = redundant(str2, str1); | |
| if (secondOcc > firstOcc) { | |
| return str2.concat(str1.substring(secondOcc)); | |
| } | |
| return str1.concat(str2.substring(firstOcc)); | |
| } | |
| public static void main(String[] args) { | |
| System.out.println("Using example: " + factorizeExtremities("1234yyabc", "abcxxxx1234")); | |
| System.out.println("Using example: " + factorizeExtremities("UUUUUUUUUUUUUU", "UUUUU")); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment