Friday, February 16, 2024

[LeetCode] Merge Strings Alternately

Problem: 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:

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


Approach: It's a simple problem to solve, you can look directly at the implementation to understand the approach.

    

Implementation in C#:

    public string MergeAlternately(string word1, string word2)
    {
        // Safety checks
        if (string.IsNullOrEmpty(word1) && string.IsNullOrEmpty(word2))
        {
            return word1;
        }
        if (string.IsNullOrEmpty(word1))
        {
            return word2;
        }
        if (string.IsNullOrEmpty(word2))
        {
            return word1;
        }

        int i = 0, j = 0;
        StringBuilder sb = new StringBuilder();
        while (i < word1.Length && j < word2.Length)
        {
            sb.Append(word1[i++]);
            sb.Append(word2[j++]);
        }

        if (i < word1.Length)
        {
            this.AppendAllChars(sb, i, word1);
        }
        if (j < word2.Length)
        {
            this.AppendAllChars(sb, j, word2);
        }

        return sb.ToString();
    }

    private void AppendAllChars(StringBuilder sb, int index, string word)
    {
        while (index < word.Length)
        {
            sb.Append(word[index++]);
        }
    }

Complexity: O(n)

No comments:

Post a Comment