I have a very specific question regarding strings in Java. Given a string, I would like to be able to make an array of strings, such that every i'th element is a string consisting of the first i characters of the given string. Like this:
public static String[] substrings(String s){
String[] list = new String[s.length()];
list[0] = "" + s.charAt(0);
for (int i = 1; i < s.length(); i++)
list[i] = list[i-1] + s.charAt(i);
return list;
}
But I heared adding strings together with '+' has time complexity O(n). This would mean my method has time complexity O(n²). Another way might be using the StringBuilder object. Like this:
public static String[] substrings(String s){
String[] list = new String[s.length()];
StringBuilder sb = new StringBuilder(s.length());
for (int i = 0; i < s.length(); i++){
sb.append(s.charAt(i));
list[i] = sb.toString();
}
return list;
}
But I have the feeling that StringBuilder.toString() has a time complexity of O(n), which means the method still has time complexity O(n²). Although I'm not certain about this, so please correct me if I'm wrong.
If I'm right about this though, is there a way to build strings in Java, and have some sort of log of all the values it's had, which doesn't require time complexity O(n²)?
And if not, is there a way of doing this in another programming language, preferably C or C++?
It just feels like a computer should be able to do this, because you are in fact able to do this with numbers. Although it does have more memory complexity with strings, so I wouldn't be too surprised if it isn't possible.