1768. Merge Strings Alternately

You are given two strings word1 and word2. Merge the strings by adding letters in alternating order, starting with word1. If a string is longer than the other, append the additional letters onto the end of the merged string.

Return the merged string.
 

Example 1:
Example 2:
Example 3:
Constraints:
  • 1 <= word1.length, word2.length <= 100
  • word1 and word2 consist of lowercase English letters.

From: LeetCode
Link: 1768. Merge Strings Alternately


Solution:

Ideas:

This function first calculates the lengths of word1 and word2, then allocates enough memory to hold the merged string. It then iterates through both word1 and word2, alternating characters from each and appending them to the merged string. If one of the strings is longer, it appends the remaining characters to the end of the merged string. Finally, the function null-terminates the merged string and returns it.

Code:
char * mergeAlternately(char * word1, char * word2) {
    // Calculate the length of both input strings
    int len1 = strlen(word1);
    int len2 = strlen(word2);
    int totalLen = len1 + len2;

    // Allocate memory for the merged string
    char *merged = (char *)malloc(totalLen + 1); // +1 for the null terminator

    if (merged == NULL) {
        // Handle memory allocation failure
        return NULL;
    }

    int i = 0, j = 0, k = 0;

    // Merge the strings alternately
    while (i < len1 && j < len2) {
        merged[k++] = word1[i++];
        merged[k++] = word2[j++];
    }

    // Append the remaining characters from word1 or word2, if any
    while (i < len1) {
        merged[k++] = word1[i++];
    }
    while (j < len2) {
        merged[k++] = word2[j++];
    }

    // Null-terminate the merged string
    merged[k] = '\0';

    return merged;
}
12-17 07:07