题目描述:
1768. 交替合并字符串 - 力扣(LeetCode) (leetcode-cn.com)
自测用例:
"abc"
"pqr"
"ab"
"pqrs"
"abcd"
"pq"
Java代码:
class Solution {
public String mergeAlternately(String sa, String sb) {
StringBuilder ans=new StringBuilder();
char[] a=sa.toCharArray(),b=sb.toCharArray();
for(int ai=0,bi=0;ai<a.length||bi<b.length;){
if(ai<a.length)ans.append(a[ai++]);
if(bi<b.length)ans.append(b[bi++]);
}
return ans.toString();
}
}
class Solution {
public String mergeAlternately(String sa, String sb) {
StringBuilder ans=new StringBuilder();
char[] a=sa.toCharArray(),b=sb.toCharArray();
for(int i=0;i<a.length||i<b.length;i++){
if(i<a.length)ans.append(a[i]);
if(i<b.length)ans.append(b[i]);
}
return ans.toString();
}
}
|