[英]Is there a way to concatenate Java strings in less than O(n) time?
My homework question involves joining strings in a particular sequence.我的作业问题涉及以特定顺序连接字符串。 We are first given the strings, followed by a set of instructions that tell us how to concatenate them;
我们首先得到字符串,然后是一组指令,告诉我们如何连接它们; finally we print the output string.
最后我们打印 output 字符串。
I have used the Kattis FastIO class to handle buffered input and output.我使用 Kattis FastIO class 来处理缓冲输入和 output。 Below is my algorithm, which iterates through the instructions to concatenate the strings.
下面是我的算法,它遍历指令以连接字符串。 I have tried making the array of normal strings, StringBuffers and StringBuilders.
我尝试过制作普通字符串、StringBuffers 和 StringBuilders 的数组。
The program seems to work as intended, but it gives a time limit error on my submission platform due to inefficiency.该程序似乎按预期工作,但由于效率低下,它在我的提交平台上给出了时间限制错误。 It seems like appending the way I did is O(n);
似乎附加我的方式是 O(n); is there any faster way?
有没有更快的方法?
public class JoinStrings {
public static void main(String[] args) {
Kattio io = new Kattio(System.in, System.out);
ArrayList<StringBuilder> stringList = new ArrayList<StringBuilder>();
int numStrings = io.getInt();
StringBuilder[] stringArray = new StringBuilder[numStrings];
for (int i = 0; i < numStrings; i++) {
String str = io.getWord();
stringArray[i] = new StringBuilder(str);
}
StringBuilder toPrint = stringArray[0];
while (io.hasMoreTokens()) {
int a = io.getInt();
int b = io.getInt();
stringArray[a-1].append(stringArray[b-1]); // this is the line that is done N times
toPrint = stringArray[a-1];
}
io.println(toPrint.toString());
io.flush();
}
}
The StringBuilder.append()
copy char from new string to existing string. StringBuilder.append()
将 char 从新字符串复制到现有字符串。 It's fast but not free.它很快但不是免费的。
Instead of keeping appending the String to the StringBuilder array, keep track of the String indexes need to appended.不是一直将字符串附加到 StringBuilder 数组,而是跟踪需要附加的字符串索引。 Then finally append the Strings stored in the print out indexes list.
然后最后 append 存储在打印输出索引列表中的字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.