Sponsored
Sponsored
This approach uses a loop to iterate through the characters in the strings by index. We initiate a loop for the length of the shorter string, adding characters alternately from each string to a result. Once the loop ends, we append the remaining part of the longer string.
Time Complexity: O(n + m), where n and m are the lengths of the two strings.
Space Complexity: O(n + m) for the resulting string.
1using System;
2
3class MergeStrings {
4 public static string MergeAlternately(string word1, string word2) {
5 var result = new System.Text.StringBuilder();
6 int i = 0, j = 0;
7 while (i < word1.Length && j < word2.Length) {
8 result.Append(word1[i++]);
9 result.Append(word2[j++]);
10 }
11 result.Append(word1.Substring(i));
12 result.Append(word2.Substring(j));
13 return result.ToString();
14 }
15
16 public static void Main() {
17 string word1 = "abc";
18 string word2 = "pqr";
19 Console.WriteLine(MergeAlternately(word1, word2));
20 }
21}
The method MergeAlternately
merges two strings by appending alternate characters using a StringBuilder
. If one string is longer, the remaining characters are added to the result. The merged string is returned in string form.
This approach uses recursion to merge the strings by alternating characters. It utilizes recursive calls to handle the process of alternately taking characters from each string, ending the recursion once one of the strings is fully consumed. The remaining part of the longer string is then joined directly to the result.
Time Complexity: O(n + m), where n and m are the lengths of the two strings.
Space Complexity: O(n + m) for call stack and resulting string in the worst case.
1def merge_alternately(word1: str, word2: str) -> str:
2
This recursive function merge_alternately
checks if either string is empty. If so, it returns the remaining part of the other string. Otherwise, it returns the first character of each string concatenated with a recursive call using the rest of the strings.