Skip to content

Commit 04c15a8

Browse files
committed
Implementing AlternativeStringArrange
1 parent fb12971 commit 04c15a8

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package com.thealgorithms.strings;
2+
3+
/**
4+
* This class provides a method to arrange two strings by alternating their characters.
5+
* If one string is longer, the remaining characters of the longer string are appended at the end.
6+
* <p>
7+
* Example:
8+
* Input: "abc", "12345"
9+
* Output: "a1b2c345"
10+
* <p>
11+
* Input: "abcd", "12"
12+
* Output: "a1b2cd"
13+
*
14+
* @author Milad Sadeghi
15+
*/
16+
public final class AlternativeStringArrange {
17+
18+
// Private constructor to prevent instantiation
19+
private AlternativeStringArrange() {
20+
throw new IllegalStateException("Utility class");
21+
}
22+
23+
/**
24+
* Arranges two strings by alternating their characters.
25+
*
26+
* @param firstString the first input string
27+
* @param secondString the second input string
28+
* @return a new string with characters from both strings arranged alternately
29+
*/
30+
public static String arrange(String firstString, String secondString) {
31+
StringBuilder result = new StringBuilder();
32+
int length1 = firstString.length();
33+
int length2 = secondString.length();
34+
int minLength = Math.min(length1, length2);
35+
36+
for (int i = 0; i < minLength; i++) {
37+
result.append(firstString.charAt(i));
38+
result.append(secondString.charAt(i));
39+
}
40+
41+
if (length1 > length2) {
42+
result.append(firstString.substring(minLength));
43+
} else if (length2 > length1) {
44+
result.append(secondString.substring(minLength));
45+
}
46+
47+
return result.toString();
48+
}
49+
}

0 commit comments

Comments
 (0)