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.
두 개의 문자열 word1과 word2가 주어집니다. word1부터 시작하여 번갈아 가며 문자를 추가하여 문자열을 병합합니다. 문자열이 다른 문자열보다 길면 추가 문자를 병합된 문자열의 끝에 추가합니다.
병합된 문자열을 반환합니다.
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.
코드 1
class Solution {
fun mergeAlternately(word1: String, word2: String): String {
var answer = ""
var l1 = 0
var l2 = 0
while (l1 < word1.length || l2 < word2.length) {
if (l1 < word1.length) {
answer += word1[l1]
}
if (l2 < word2.length) {
answer += word2[l2]
}
l1++
l2++
}
return answer
}
}
코드 2
class Solution {
fun mergeAlternately(word1: String, word2: String): String {
val res = StringBuilder()
var i = 0
var j = 0
while (i < word1.length && j < word2.length) {
res.append(word1[i])
res.append(word2[j])
i++
j++
}
res.append(word1.drop(i))
res.append(word2.drop(j))
return res.toString()
}
}
'LeetCode > Two Pointers' 카테고리의 다른 글
[LeetCode][Kotlin] 557. Reverse Words in a String III (0) | 2024.10.19 |
---|---|
[LeetCode][Kotlin] 80. Remove Duplicates from Sorted Array II (0) | 2024.10.04 |
[LeetCode][Kotlin] 844. Backspace String Compare (0) | 2024.10.01 |