forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAlternativeStringArrange.java
More file actions
48 lines (42 loc) · 1.43 KB
/
AlternativeStringArrange.java
File metadata and controls
48 lines (42 loc) · 1.43 KB
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
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();
}
}