Our initial strategy revolves around the concept of interleaving: taking two sequences and combining them into one by alternating elements from each. The primary concern is ensuring that we handle strings of unequal length gracefully, appending any remaining characters from the longer string after the interleaving process.
// MARK: - Test Cases
let solution = Solution()
// Test Case 1
let str1_1 = "ABCABC"
let str2_1 = "ABC"
print("Test Case 1: \\(solution.mergeAlternately(str1_1, str2_1))")
// Expected Output: "AABBCCABC"
// Test Case 2
let str1_2 = "ABABAB"
let str2_2 = "ABAB"
print("Test Case 2: \\(solution.mergeAlternately(str1_2, str2_2))")
// Expected Output: "AABBAABBAB"
// Test Case 3
let str1_3 = "LEET"
let str2_3 = "CODE"
print("Test Case 3: \\(solution.mergeAlternately(str1_3, str2_3))")
// Expected Output: "LCEOEDTE"
// Test Case 4
let str1_4 = "Hello"
let str2_4 = "World"
print("Test Case 4: \\(solution.mergeAlternately(str1_4, str2_4))")
// Expected Output: "HWeolrllod"
// Test Case 5
let str1_5 = "12345"
let str2_5 = "abc"
print("Test Case 5: \\(solution.mergeAlternately(str1_5, str2_5))")
// Expected Output: "1a2b3c45"
Approaches
word1
and word2
, respectively.class Solution {
func mergeAlternately(_ word1: String, _ word2: String) -> String {
var mergedString = ""
let minLength = min(word1.count, word2.count)
let char1 = Array(word1)
let char2 = Array(word2)
for i in 0..<minLength {
mergedString.append(char1[i])
mergedString.append(char2[i])
}
if word1.count > minLength {
mergedString.append(String(char1[minLength...]))
} else if word2.count > minLength {
mergedString.append(String(char2[minLength...]))
}
return mergedString
}
}
zip
function to combine the characters of word1
and word2
into tuples, then flatten this structure into a single string using flatMap
. Finally, append any remaining characters from the longer string.