LeetCode //C - 1768. Merge Strings Alternately

2023-12-13 06:47:09

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:

Input: word1 = “abc”, word2 = “pqr”
Output: “apbqcr”
Explanation: The merged string will be merged as so:
word1: a b c
word2: p q r
merged: a p b q c r

Example 2:

Input: word1 = “ab”, word2 = “pqrs”
Output: “apbqrs”
Explanation: Notice that as word2 is longer, “rs” is appended to the end.
word1: a b
word2: p q r s
merged: a p b q r s

Example 3:

Input: word1 = “abcd”, word2 = “pq”
Output: “apbqcd”
Explanation: Notice that as word1 is longer, “cd” is appended to the end.
word1: a b c d
word2: p q
merged: a p b q c d

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;
}

文章来源:https://blog.csdn.net/navicheung/article/details/134939861
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。