gpt4 book ai didi

java - 为什么使用数组而不是字符串可以减少内存消耗和执行时间?

转载 作者:行者123 更新时间:2023-11-30 05:38:39 25 4
gpt4 key购买 nike

Given the string in the form of char array. Modify it the way that all the exclamation point symbols '!' are shifted to the start of the array, and all ohters are in the same order. Please write a method with a single argument of type char[]. Focus on either memory and time consumption of alghoritm.

我收到的反馈:可以使用数组而不是字符串。我在哪里可以找到有关内存的信息?

public static String formatString(char[] chars) {
StringBuilder exclamationSymbols = new StringBuilder();
StringBuilder otherSymbols = new StringBuilder();

for (char c : chars) {
if (c == '!') {
exclamationSymbols.append(c);
} else {
otherSymbols.append(c);
}
}

return (exclamationSymbols.toString() + otherSymbols.toString());
}

最佳答案

您可以使用 char[] 更快地完成此操作比 StringBuilder因为:

  • 一个StringBuilder只是 char[] 的包装,所以它不可能更快。间接意味着速度会变慢。
  • 您确切知道结果的长度,因此您可以分配最小大小的 char[]你需要的。与 StringBuilder ,您可以预先调整它的大小,但有两个 StringBuilder你不能完全做到这一点,所以你要么必须过度分配长度(例如,使两者的长度与 chars 相同),要么依赖 StringBuilder在内部调整自身大小(这会比不慢;并且使用更多内存)。

我的想法是使用两个整数指针指向您将在字符串中写入字符的下一个位置:一个从数组的开头开始,另一个从末尾开始;当您完成输入时,两个指针将靠得更近。

处理完整个输入后,结果数组中与“结束指针”对应的部分将向后,因此将其反转。

你可以这样做:

char[] newChars = new char[chars.length];
int left = 0;
int right = chars.length;

for (char c : chars) {
if (c == '!') {
newChars[left++] = c;
} else {
newChars[--right] = c;
}
}

// Reverse the "otherSymbols".
for (int i = right, j = newChars.length - 1; i < j; ++i, --j) {
char tmp = newChars[i];
newChars[i] = newChars[j];
newChars[j] = tmp;
}

return new String(newChars);

Ideone demo

关于java - 为什么使用数组而不是字符串可以减少内存消耗和执行时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56148337/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com