leetcode_打卡1
解答:
思路: 模拟即可,字符串的提取:
a.charAt(i)
class Solution {
public String mergeAlternately(String word1, String word2) {
String result="";
int m=word1.length();
int n=word2.length();
int i=0,j=0;
while(i<m && j<n){
result=result+word1.charAt(i);
i++;
result=result+word2.charAt(j);
j++;
}
while(i<m) {
result=result+word1.charAt(i);
i++;
}
while(j<n) {
result=result+word2.charAt(j);
j++;
}
return result;
}
}
优化:
class Solution {
public String mergeAlternately(String s1, String s2) {
int n = s1.length(), m = s2.length(), i = 0, j = 0;
StringBuilder sb = new StringBuilder();
while (i < n || j < m) {
if (i < n) sb.append(s1.charAt(i++));
if (j < m) sb.append(s2.charAt(j++));
}
return sb.toString();
}
}
作者:AC_OIer
链接:https://leetcode.cn/problems/merge-strings-alternately/solution/by-ac_oier-rjve/
来源:力扣(LeetCode)
标签:String,int,length,sb,打卡,leetcode
From: https://www.cnblogs.com/ZLey/p/17305573.html