Stringbuilder

Naive solution

String joinWords(String[] words) {
    String sentence = "";
    for (String w : words) {
        sentence = sentence + w;
    }
    return sentence;
}
Time complexity

For simplicity, assume n strings of equal length x. The first iteration copies x chars, the second copies 2x, and so on until the final iteration copies nx chars.

O(x + 2x + ... + nx) = O(xn(n-1)/2) = O(xn^2)

Stringbuilder implementation

Uses a resizable array:

import java.util.Arrays;

public class MyStringBuilder {
    private char[] buffer;
    private int currentSize;

    public MyStringBuilder() {
        currentSize = 5;
        buffer = new char[currentSize];
    }

    public void append(String s) {
        for (char c : s.toCharArray()) {
            if (currentSize <= buffer.length) {
                resize();
            }
            buffer[currentSize] = c;
            currentSize++;
        }
    }

    private void resize() {
        int newSize = buffer.length * 2;
        buffer = Arrays.copyOf(buffer, newSize);
    }

    public String toString() {
        return new String(buffer, 0, currentSize);
    }
}

results matching ""

    No results matching ""