Search code examples
javastringstringbuilder

What's the wrong with StringBuilder in code


class Solution {
    public String mergeAlternately(String word1, String word2) {
        int length = word1.length() + word2.length();
        StringBuilder ans = new StringBuilder(length);
        int left = 0, right = 0, current = 0;
        System.out.println(ans.length());
        while(current < ans.length()) {
            System.out.println("called");
            if(left >= word1.length()) {
                ans.append(word2.charAt(right));
                right++;
            }
            else if(right >= word2.length()) {
                ans.append(word2.charAt(left));
                left++;
            }
            else if(current % 2 == 0) {
                ans.append(word1.charAt(left));
                left++;
            }
            else {
                ans.append(word2.charAt(right));
                right++;
            }
            current++;
        }
        return ans.toString();
    }
}

The problem is=> 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.

I have tried:

Input: word1 = "abc", word2 = "pqr"

Expected Output: "apbqcr"

my Output: ""


Solution

  • Initial capacity versus length

    Your code:

    StringBuilder ans = new StringBuilder(length);
    

    Defines an initial capacity for the string bulder, but does not fill it with any text. See the Javadoc:

    Constructs a string builder with no characters in it and an initial capacity specified by the capacity argument.

    In other words, new StringBuilder( 42 ).length() returns 0 zero.

    So your test while(current < ans.length()) never returns true. Your current variable is never less than zero, never negative.

    char is legacy

    The char type has been essentially broken since Java 2, legacy since Java 5. As a 16-bit value, a char cannot represent most characters.

    To work with individual characters, learn to use code point integers.

    Search Stack Overflow to learn more as this has been covered many times already.