Posts Merge Strings Alternately
Post
Cancel

Merge Strings Alternately

Problem Description

You are given two strings word1 and word2. Merge the strings by adding letters in alternating order, starting with word1. If a string is longer than the other, append the additional letters onto the end of the merged string.

Return the merged string.

leetcode

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {

    public String mergeAlternately(String word1, String word2) {

        StringBuffer sb = new StringBuffer();

        int idx = 0;

        int n = word1.length();
        int m = word2.length();

        while(idx < n && idx < m){

            sb.append(String.valueOf(word1.charAt(idx)));
            sb.append(String.valueOf(word2.charAt(idx)));

            idx++;

        }

        while(idx < n)
            sb.append(String.valueOf(word1.charAt(idx++)));

        while(idx < m)
            sb.append(String.valueOf(word2.charAt(idx++)));

        return sb.toString();

    }

}
This post is licensed under CC BY 4.0 by the author.