Leetcode 75: 1768. Merge Strings Alternately

In this blog post, we'll examine a problem from Leetcode - "Merge Strings Alternately". We'll walk through a PHP solution and break it down for better understanding. The problem asks to merge two strings by adding letters in alternating order, starting with the first string. If one string is longer than the other, the additional letters should be appended to the end of the merged string.


The PHP solution given below does exactly that:

class Solution {


    /**

     * @param String $word1

     * @param String $word2

     * @return String

     */

    function mergeAlternately($word1, $word2) {

        $word1Length = strlen($word1);

        $word2Length = strlen($word2);

        $output = '';

        $remainder = '';

        $loopLength = min($word1Length, $word2Length);

        if ($word1Length > $word2Length) {

            $remainder = substr($word1, $word2Length);

        } else if ($word1Length < $word2Length) {

            $remainder = substr($word2, $word1Length);

        }

        for ($i=0; $i < $loopLength; $i++) {

            $output .= $word1[$i];

            $output .= $word2[$i];

        }

        return $output.$remainder;

    }

}

How Does The Code Work?

Step 1

First, it finds the length of each input string using PHP's built-in strlen() function.

$word1Length = strlen($word1);

$word2Length = strlen($word2);


Step 2

We initialize two variables: $output (the final result, an empty string at first) and $remainder (a string variable to keep the remaining part of the longer string).

$output = '';

$remainder = '';


Step 3

The code determines the shortest length between the two input strings with PHP's min() function. This length will be used as the limit for the main loop, which combines the strings.

$loopLength = min($word1Length, $word2Length);


Step 4

The code then checks which string is longer by comparing their lengths. It uses the substr() function to extract the remaining characters from the longer string and stores them in $remainder.

if ($word1Length > $word2Length) {

    $remainder = substr($word1, $word2Length);

} else if ($word1Length < $word2Length) {

    $remainder = substr($word2, $word1Length);

}

Step 5

In the main loop, it iteratively adds characters from both strings to $output in an alternating manner, starting with word1.

for ($i=0; $i < $loopLength; $i++) {

    $output .= $word1[$i];

    $output .= $word2[$i];

}

Step 6

Finally, it appends the $remainder to the $output and returns the result.

return $output.$remainder;


And that's it! This PHP solution for the "Merge Strings Alternately" problem effectively merges the two strings in the desired manner. 

I code fastest in PHP, as it's been my main language for a while, but lets explore some of my other languages since this one was so quick and easy.


Java Solution

In Java, you would use the StringBuilder class, which is more efficient for string concatenation in loops compared to the '+' operator. The steps would be similar: iterate over both strings, appending one character at a time from each. If one string is longer, append the remaining characters at the end.

class Solution {

    public String mergeAlternately(String word1, String word2) {

        StringBuilder sb = new StringBuilder();

        int i = 0, j = 0;

        while (i < word1.length() && j < word2.length()) {

            sb.append(word1.charAt(i++));

            sb.append(word2.charAt(j++));

        }

        while (i < word1.length()) {

            sb.append(word1.charAt(i++));

        }

        while (j < word2.length()) {

            sb.append(word2.charAt(j++));

        }

        return sb.toString();

    }

}

Python Solution

Python has some powerful built-in functions, and a zip() function is a perfect fit for this problem. You would use a list comprehension to iterate over both strings at once, adding one character at a time from each. If one string is longer, Python's slicing feature helps to append the remaining characters at the end.

class Solution:

    def mergeAlternately(self, word1, word2):

        merged = [char for pair in zip(word1, word2) for char in pair]

        if len(word1) > len(word2):

            merged.append(word1[len(word2):])

        else:

            merged.append(word2[len(word1):])

        return "".join(merged)

It's interesting to see how each language has its own unique tools and features to deal with the problem efficiently!


Comments

Popular posts from this blog

Defending Against Ettercap Attacks: A Brief Overview

Leetcode Two Sum Problem in three different languages