classSolution { public: string mergeAlternately(string word1, string word2){ int m = word1.size(), n = word2.size(); int i = 0, j = 0; string ans; ans.reserve(m + n); while (i < m || j < n) { if (i < m) { ans.push_back(word1[i]); ++i; } if (j < n) { ans.push_back(word2[j]); ++j; } } return ans; } };
[sol1-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution { public String mergeAlternately(String word1, String word2) { intm= word1.length(), n = word2.length(); inti=0, j = 0;
StringBuilderans=newStringBuilder(); while (i < m || j < n) { if (i < m) { ans.append(word1.charAt(i)); ++i; } if (j < n) { ans.append(word2.charAt(j)); ++j; } } return ans.toString(); } }
[sol1-C#]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
publicclassSolution { publicstringMergeAlternately(string word1, string word2) { int m = word1.Length, n = word2.Length; int i = 0, j = 0;
StringBuilder ans = new StringBuilder(); while (i < m || j < n) { if (i < m) { ans.Append(word1[i]); ++i; } if (j < n) { ans.Append(word2[j]); ++j; } } return ans.ToString(); } }
[sol1-Python3]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution: defmergeAlternately(self, word1: str, word2: str) -> str: m, n = len(word1), len(word2) i = j = 0
ans = list() while i < m or j < n: if i < m: ans.append(word1[i]) i += 1 if j < n: ans.append(word2[j]) j += 1 return"".join(ans)
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
var mergeAlternately = function(word1, word2) { const m = word1.length, n = word2.length; let i = 0, j = 0;
const ans = []; while (i < m || j < n) { if (i < m) { ans.push(word1[i]); ++i; } if (j < n) { ans.push(word2[j]); ++j; } } return ans.join(''); };
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13
funcmergeAlternately(word1, word2 string)string { n, m := len(word1), len(word2) ans := make([]byte, 0, n+m) for i := 0; i < n || i < m; i++ { if i < n { ans = append(ans, word1[i]) } if i < m { ans = append(ans, word2[i]) } } returnstring(ans) }
复杂度分析
时间复杂度:O(m+n),其中 m 和 n 分别是字符串 word}_1 和 word}_2 的长度。