我正在编写一个程序,让用户输入一个字符串并显示最大的递增排序的字符子序列。然而,我的程序是将字符添加到数组中,并创建多个等于字符串长度的数组。
我得到的例子是:
Enter a string: Welcome
Result: Welo
我的程序没有错误,但输入字符串“Welcome”时的输出是:
[W, e, l, c, o, m, e]
[W, e, l, c, o, m, e]
[W, e, l, c, o, m, e]
[W, e, l, c, o, m, e]
[W, e, l, c, o, m, e]
[W, e, l, c, o, m, e]
[W, e, l, c, o, m, e]
import java.util.ArrayList;
import java.util.Scanner;
public class orderSequence {
public static void main(String[] args) {
// TODO Auto-generated method stub
// Create Scanner for input/output
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string: ");
String input = sc.nextLine();
ArrayList<Character> al = new ArrayList();
for (int i = 0; i < input.length(); i++) {
ArrayList<Character> list = new ArrayList<Character>();
list.add(input.charAt(i));
for(int j = i + 1; j < input.length(); j++) {
if(input.charAt(j) > list.lastIndexOf(list)) {
list.add(input.charAt(j));
}
}
if (list.size() > al.size()) {
al.clear();
al.addAll(list);
}
list.clear();
}
for (int i = 0; i < al.size(); i++) {
System.out.println(al);
}
}
}
最佳答案
问题发生在 if(input.charAt(j) > list.lastIndexOf(list))
行上。 lastIndexOf
函数返回您传入的对象最后出现的索引。好吧,您正在传递列表本身,而 list
中没有任何地方是 list
元素本身之一。因此 lastIndexOf
方法返回 -1。因此,您执行 character at j > -1
这始终为 true,这就是为什么您的方法不断返回数组中的整个字符串。
查看此处,了解有关 lastIndexOf 的更多信息.
修复方法的方法是执行 if(input.charAt(j) > list.get(list.size() - 1))
它重复 4 次的原因是因为底部的 for
循环。 al
的大小为 4,因此 for 循环运行其中的代码 4 次,因此它将打印 al
4 次。
关于Java 最大递增有序子序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46064765/