Hi there !
This is going to be my first post on this platform. I decided to write down everything I find useful so I don't forget it easily. I'm starting with this LeetCode series because I'm studying Data Structures and Algorithms (DSA).
The first challenge is called Merge Strings Alternately. In this problem, we are given 2 strings as parameters, and we need to merge them by adding letters in alternating order.
For example:
word1: abc
word2: pqr
output: apbqcr
Example 2:
word1: ab
word2: pqrs
output: apbqrs
Solution
We'll start by creating a variable 'word' and initializing it as an empty string, along with 'left' and 'right' variables starting at 0. We'll use the left and right variables as indices for word1 and word2 respectively as we iterate through them using a while loop.
The while loop condition will check if either the left or right pointer is still within the index range. If both pointers are within range, we'll append each character from word1 and word2 to our previously created variable 'word', and then increment the left and right values to move to the next indices.
Then we'll check for the case where one of the pointers goes out of range. In this situation, we just need to append the remaining characters from the other string and break out of the while loop.
Finally, we return the 'word' variable that contains our merged result.
func mergeAlternately(_ word1: String, _ word2: String) -> String {
var word = String()
var (left, right) = (0, 0)
while left < word1.count || right < word2.count {
if left < word1.count && right < word2.count {
word.append(word1[word1.index(word1.startIndex, offsetBy: left)])
word.append(word2[word2.index(word2.startIndex, offsetBy: right)])
left += 1
right += 1
} else if left < word1.count {
word.append(contentsOf: word1[word1.index(word1.startIndex, offsetBy: left)...])
break
} else {
word.append(contentsOf: word2[word2.index(word2.startIndex, offsetBy: right)...])
break
}
}
return word
}
Top comments (0)