[LeetCode] 1768. Merge Strings Alternately

Semidragon·2023년 8월 7일
0

CodingTest

목록 보기
1/80
post-thumbnail

1. Question

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

2. Thoughts

  1. First get the length of the length of shorter
  2. traverse through both words with the amount of shorter length, and add each char
  3. once traverse finishes, add the rest for the longer

3. Tips learned

3.1 Use for loop instead of for loop:

If you want to iterate over the length of a word using a while loop, you can do something like this:

word = "example"
i = 0

while i < len(word):
    print(word[i])
    i += 1

However, using a for loop with a range is more Pythonic and easier to understand:

word = "example"

for i in range(len(word)):
    print(word[i])

Even better, if you just want to loop over each character in the word, you can directly iterate over the string:

word = "example"

for char in word:
    print(char)

The last method is the most Pythonic and should be preferred when you just need to access the characters in a string without needing the index. If you do need the index, you can use enumerate:

word = "example"

for i, char in enumerate(word):
    print(f"Character at index {i} is {char}")

In summary, while you can use a while loop, a for loop is usually more readable and better suited for such tasks in Python.

3.2 For ternary conditional operator use "if else"

In many programming languages, the ? : construct is known as the ternary conditional operator, sometimes colloquially referred to as the "ternary operator" or just "ternary." In Python, there's an equivalent expression, but it's structured differently. It's sometimes called the "conditional expression."

Here's how it works in Python:

value_if_true if condition else value_if_false

For example:

x = 5
message = "Even" if x % 2 == 0 else "Odd"
print(message)  # Output: Odd

So, while Python doesn't use the ? : syntax, it does offer a concise way to choose between two values based on a condition.

4. My solution

class Solution:
    def mergeAlternately(self, word1: str, word2: str) -> str:
        output_word = ""
        longer = word1 if len(word1) >= len(word2) else word2
        shorter_len = len(word1) if len(word1) <= len(word2) else len(word2)
        for i in range(shorter_len):
            output_word += word1[i] + word2[i]
        output_word += longer[shorter_len:]
        return output_word

5. AI Solution and Improvements

class Solution:
    def mergeAlternately(self, word1: str, word2: str) -> str:
        # Using zip to get pairs of characters from both words
        merged = ''.join(a + b for a, b in zip(word1, word2))
        
        # Using slicing to get the remaining part of the longer word
        return merged + word1[len(merged) // 2:] + word2[len(merged) // 2:]

Here's what was changed:

  1. Used the zip function to pair characters from word1 and word2. This eliminates the need to determine which word is shorter.
  2. Removed explicit loops by using list comprehensions.
  3. Made use of string concatenation and slicing to append the remaining part of the longer string.

The code is now more concise and utilizes built-in Python features for better readability and performance.

profile
Semidragon's network [CS undergrad @ Sungkyunkwan University | Networks + System @ CSI]

1개의 댓글

comment-user-thumbnail
2023년 8월 7일

좋은 정보 얻어갑니다, 감사합니다.

답글 달기