gpt4 book ai didi

java - 对字符串进行排序时,数组中的字符被删除

转载 作者:行者123 更新时间:2023-12-02 10:20:31 25 4
gpt4 key购买 nike

我正在编写一个类来按字典顺序打印给定的字符串,但在 final方法“reverseOrder()”中,数组会自动从中删除值(我想)。方法reverseOrder正在删除选定字符串的一些字符,例如“dkhc”。谢谢

调试显示值已正确添加到数组中。

public class LexicalOrder {
static String biggerIsGreater(String w) {
String finalString = "";
char[] charArr = w.toCharArray();
int largestX = -1;
// Find the largest x such that P[x]<P[x+1].
// (If there is no such x, P is the last permutation.)
for (int i = 0; i < charArr.length - 1; i++) {
if (charArr[i] < charArr[i + 1]) {
largestX = i;
}
}
if (largestX == -1) {
finalString = "no answer";
}
int largestY = -1;
if (largestX != -1) {
for (int j = 0; j < charArr.length; j++) {
if (charArr[largestX] < charArr[j]) {
largestY = j;
}
}
charArr = swap(charArr, largestX, largestY);
charArr = reverseOrder(charArr, largestX + 1);
finalString = new String(charArr);
}
return finalString;
}

// Method to swap characters in index largestX and largestY
public static char[] swap(char[] a, int largestX, int largestY) {
char temp = a[largestY];
a[largestY] = a[largestX];
a[largestX] = temp;
return a;
}

// Method to reverse the order of the array from the index
// largestX + 1 to n (n being last element of array)
public static char[] reverseOrder(char[] a, int index) {
int step = 0;
char[] newArr = new char[a.length];
for (int j = 0; j < index; j++) {
System.out.println(j);
newArr[j] = a[j]; // adding elements to new arr till index=largestX
System.out.println(newArr[j] = a[j]);
}
for (int i = index; i < a.length; i++) {
System.out.println(i);
newArr[index] = a[a.length - step - 1]; // adding remaining values but with reversing order
System.out.println(newArr[index] = a[a.length - step - 1]);
step++;
}
for (char c : newArr)
System.out.println(c);
return newArr;
}

public static void main(String[] args) {
System.out.println(biggerIsGreater("dkhc"));
}
}

预期的是= hcdk。

但是我得到的是= hk

我运行该方法进行检查,它清楚地将这些元素添加到方法“reverseOrder()”中的“newArr”数组中,如下所示。

0
h
1
c
2
d
3
k

输出 - hk(和两个空格)

由于某种原因,这两个字符被两个空格替换。P.S:我正在按照此处提到的步骤link进行操作

注意:它适用于某些单词,例如“lmno,dcba等”

最佳答案

你错过的是index++。在 reverseOrder 方法中,增量 index++ 将为您提供 hcdk 预期输出。

public static char[] reverseOrder(char[] a, int index) {
int step = 0;
char[] newArr = new char[a.length];
for (int j = 0; j < index; j++) {
System.out.println(j);
newArr[j] = a[j]; // adding elements to new arr till index=largestX
System.out.println(newArr[j] = a[j]);
}
for (int i = index; i < a.length; i++) {
System.out.println(i);
newArr[index] = a[a.length - step - 1]; // adding remaining values
// but with reversing order
System.out.println(newArr[index] = a[a.length - step - 1]);
step++;index++;
}
for (char c : newArr)
System.out.println(c);
return newArr;
}

在您的情况下,由于数组中的 2 和 3 项为空,索引值不会增加。

关于java - 对字符串进行排序时,数组中的字符被删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54374073/

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