DEV: Implementing Alternative String Arrange (#6551)

This commit is contained in:
Milad Sadeghi
2025-09-29 13:43:50 +03:30
committed by GitHub
parent fb12971fd6
commit ef681e844d
2 changed files with 71 additions and 0 deletions

View File

@@ -0,0 +1,48 @@
package com.thealgorithms.strings;
/**
* This class provides a method to arrange two strings by alternating their characters.
* If one string is longer, the remaining characters of the longer string are appended at the end.
* <p>
* Example:
* Input: "abc", "12345"
* Output: "a1b2c345"
* <p>
* Input: "abcd", "12"
* Output: "a1b2cd"
*
* @author Milad Sadeghi
*/
public final class AlternativeStringArrange {
// Private constructor to prevent instantiation
private AlternativeStringArrange() {
}
/**
* Arranges two strings by alternating their characters.
*
* @param firstString the first input string
* @param secondString the second input string
* @return a new string with characters from both strings arranged alternately
*/
public static String arrange(String firstString, String secondString) {
StringBuilder result = new StringBuilder();
int length1 = firstString.length();
int length2 = secondString.length();
int minLength = Math.min(length1, length2);
for (int i = 0; i < minLength; i++) {
result.append(firstString.charAt(i));
result.append(secondString.charAt(i));
}
if (length1 > length2) {
result.append(firstString.substring(minLength));
} else if (length2 > length1) {
result.append(secondString.substring(minLength));
}
return result.toString();
}
}

View File

@@ -0,0 +1,23 @@
package com.thealgorithms.strings;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
class AlternativeStringArrangeTest {
// Method to provide test data
private static Stream<Object[]> provideTestData() {
return Stream.of(new Object[] {"abc", "12345", "a1b2c345"}, new Object[] {"abcd", "12", "a1b2cd"}, new Object[] {"", "123", "123"}, new Object[] {"abc", "", "abc"}, new Object[] {"a", "1", "a1"}, new Object[] {"ab", "12", "a1b2"}, new Object[] {"abcdef", "123", "a1b2c3def"},
new Object[] {"ab", "123456", "a1b23456"});
}
// Parameterized test using the provided test data
@ParameterizedTest(name = "{0} and {1} should return {2}")
@MethodSource("provideTestData")
void arrangeTest(String input1, String input2, String expected) {
assertEquals(expected, AlternativeStringArrange.arrange(input1, input2));
}
}