1768. Merge Strings Alternately
class Solution {
public:
string mergeAlternately(string word1, string word2) {
const int n = min(word1.length(), word2.length());
string prefix;
for (int i = 0; i < n; ++i) {
prefix += word1[i];
prefix += word2[i];
}
return prefix + word1.substr(n) + word2.substr(n);
}
};
class Solution:
def mergeAlternately(self, word1: str, word2: str) -> str:
prefix: str = ""
n = min(len(word1), len(word2))
for i in range(n):
prefix += word1[i]
prefix += word2[i]
return prefix + word1[n:] + word2[n:]
func mergeAlternately(word1 string, word2 string) string {
prefix := ""
n := min(len(word1), len(word2))
for i := 0; i < n; i++ {
prefix += string(word1[i])
prefix += string(word2[i])
}
return prefix + word1[n:] + word2[n:]
}
impl Solution {
fn merge_alternately(word1: String, word2: String) -> String {
let mut result = String::with_capacity(word1.len() + word2.len());
let mut word1 = word1.chars();
let mut word2 = word2.chars();
loop {
match (word1.next(), word2.next()) {
(Some(c1), Some(c2)) => {
result.push(c1);
result.push(c2);
}
(Some(c1), None) => {
result.push(c1);
}
(None, Some(c2)) => {
result.push(c2);
}
(None, None) => break,
}
}
result
}
}
Last updated