我的答案:
class Solution { public: string result; int i=0,j=0; string mergeAlternately(string word1, string word2) { if(word1.length()<1||word2.length()>100){ return 0; } if(word1.size()<word2.size()){ while(i<word1.size()){ result+=word1[i++]; result+=word2[j++]; } while(i<word2.size()){ result+=word2[i++]; } return result; }else{ while(i<word2.size()){ result+=word1[i++]; result+=word2[j++]; } while(j<word1.size()){ result+=word1[j++]; } return result; } } };官方解答:
class Solution { 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; } };
更优解:
class Solution { public: string mergeAlternately(string word1, string word2) { string res; int i = 0, j = 0; while (i < word1.size() || j < word2.size()) { if (i < word1.size()) res += word1[i++]; if (j < word2.size()) res += word2[j++]; } return res; } };
标签:string,int,word2,1768,word1,ans,size From: https://www.cnblogs.com/fengziyi/p/17935088.html