解题思路:根据题意,选用合适的数据结构。这里需要构造新字符串,StringBuilder提供 append() 追加字符的方法,比数组更方便。
代码
class Solution {
public String mergeAlternately(String word1, String word2) {
// 取出短串的长度
int minLen = Math.min(word1.length(), word2.length());
StringBuilder sb = new StringBuilder();
for(int i=0; i<minLen; i++){
sb.append(word1.charAt(i)).append(word2.charAt(i));
}
// 追加后续的
sb.append(word1.substring(minLen)).append(word2.substring(minLen));
return sb.toString();
}
}
参考链接
https://leetcode.cn/problems/merge-strings-alternately/discussion/comments/2105197