leetcode_打卡1

leetcode_打卡1

题目:1768. 交替合并字符串

解答:

思路: 模拟即可,字符串的提取:

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)
posted @ 2023-04-11 11:09  ZLey  阅读(5)  评论(0编辑  收藏  举报