0% found this document useful (0 votes)
12 views

Leet Code Questions

This document discusses a LeetCode question to merge two strings alternately. It provides three code samples that use different approaches like StringBuilder and pointers to solve the problem in linear time and constant space.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Leet Code Questions

This document discusses a LeetCode question to merge two strings alternately. It provides three code samples that use different approaches like StringBuilder and pointers to solve the problem in linear time and constant space.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Leet Code Questions

class Solution {

public String mergeAlternately(String word1, String word2) {


StringBuilder s = new StringBuilder();
int i=0,j=0;
while(i<word1.length()&&j<word2.length())
{
s.append(word1.charAt(i)).append(word2.charAt(j));
i++;
j++;
}
s.append(word1.substring(i)).append(word2.substring(j));
return s.toString();
}
}

Code Sample (Runtime: 1ms)

class Solution {

public String mergeAlternately(String word1, String word2) {

StringBuilder result = new StringBuilder();

for(int i = 0; i < word1.length() || i < word2.length(); i++){

if(i < word1.length()){

result.append(word1.charAt(i));

if(i < word2.length()){

result.append(word2.charAt(i));

return result.toString();

}
class Solution {

public String mergeAlternately(String word1, String word2) {

int length1 = word1.length();

int length2 = word2.length();

int pointer = 0;

StringBuilder sb = new StringBuilder();

while(pointer < length1 && pointer < length2){

sb.append(word1.charAt(pointer));

sb.append(word2.charAt(pointer));

pointer++;

if(pointer >= length1){

sb.append(word2.substring(pointer));

}else if(pointer >= length2){

sb.append(word1.substring(pointer));

return sb.toString();

You might also like