[LeetCode][JAVA] 1768. Merge Strings Alternately

탱귤생귤·2023년 10월 26일
0

LeetCode

목록 보기
1/16

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

Using two pointer reduced the time to append the alphabet.

My ans

package Merge_Strings_Alternately_1768;

public class Solution {
	public static void main(String[] args) {
		String word1 = "abc";
		String word2 = "qrs";
		mergeAlternately(word1, word2);
	}

	public static void mergeAlternately(String word1, String word2) {
		 StringBuilder sb1=new StringBuilder(word1);
		 StringBuilder sb2=new StringBuilder(word2);
		 StringBuilder ans=new StringBuilder();
		 
		 int l= sb1.length()<=sb2.length() ? sb1.length():sb2.length();
		 
		 for(int i=0; i<l; i++) {
			 ans.append(sb1.charAt(i)).append(sb2.charAt(i));
		 }
		 
		 if(sb1.length()!=sb2.length()) {
			 StringBuilder tmp=sb1.length()<sb2.length() ? sb2:sb1;
			 ans.append(tmp.substring(l));
		 }
		 
		 
	        System.out.println(ans);
	}
}
Runtime: 1 ms
Memory Usage: 40.7 MB

Solution

class Solution {
    public String mergeAlternately(String word1, String word2) {
        int i=0;
        int j=0;
        int len1=word1.length();
        int len2=word2.length();
        
        StringBuilder sb=new StringBuilder();
        
        while(i<len1 || j<len2){
            if(i<len1){
                sb.append(word1.charAt(i++));   
            }
            if(j<len2){
                sb.append(word2.charAt(j++));   
            }
        }
        
        return sb.toString();
    }
}

0개의 댓글