[코테 풀이] Merge Strings Alternately

시내·2024년 6월 7일
0

Q_1768) Merge Strings Alternately

출처 : https://leetcode.com/problems/merge-strings-alternately/?envType=study-plan-v2&envId=programming-skills

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.

class Solution {
    public String mergeAlternately(String word1, String word2) {
        String longerWord = word1.length() <= word2.length() ? word2 : word1;
        String shorterWord = word1.length() > word2.length() ? word2 : word1;
        String res = "";
        for (int s = 0; s < shorterWord.length(); s++) {
            res += word1.charAt(s);
            res += word2.charAt(s);
        }
        res += longerWord.substring(shorterWord.length());
        return res;
    }
}
profile
contact 📨 ksw08215@gmail.com

0개의 댓글