본문 바로가기
JAVA

[리트코드/자바] Merge Strings Alternately

by 동백05 2023. 7. 16.

https://leetcode.com/problems/merge-strings-alternately/

 

Merge Strings Alternately - LeetCode

Can you solve this real interview question? Merge Strings Alternately - 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 le

leetcode.com

class Solution {
    public String mergeAlternately(String word1, String word2) {
        int length1=word1.length();
        int length2=word2.length();
        String merged_word="";

        if(length1==length2){
            for(int i=0;i<length1;i++){
                merged_word+=word1.substring(i,i+1)+word2.substring(i,i+1);
            }
        }else if(length1>length2){
            for(int i=0;i<length2;i++){
                merged_word+=word1.substring(i,i+1)+word2.substring(i,i+1);
            }
            merged_word+=word1.substring(length2);
        }else{
            for(int i=0;i<length1;i++){
                merged_word+=word1.substring(i,i+1)+word2.substring(i,i+1);
            }
            merged_word+=word2.substring(length1);
        }
        return merged_word;
    }
}

댓글