我正在编写一个类,以按字典顺序打印给定的字符串,但是在最终方法“ 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(和两个空格)
由于某些原因,两个字符被两个空格替换。 附注:我正在按照此处link
所述的步骤进行操作注意:它适用于某些单词,例如“ lmno,dcba等”
答案 0 :(得分:1)
您错过的是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项为空,因此索引值没有增加。