【发布时间】:2019-09-23 15:19:16
【问题描述】:
我有一些输入作为字符串。我需要做一些以下事情:
- 字数应按长度递增的顺序打印;
- 重复多次的单词将被忽略。
- 字号大小相同后要打印的字号。
例如:Input : the Black lion was bigger than the red lion;
Output : the was 3 than black 4 ... so on....till the end!
我已尝试使用 Array List 并对它们进行排序。但结果并不像问题那样准确。 任何人都可以帮助实现没有列表、树或正则表达式的结果。
import java.util.*;
class Sorted implements Comparator<String> {
public int compare(String o1, String o2) {
if (o1.length() < o2.length()) {
return -1;
} else if (o1.length() > o2.length()) {
return 1;
} else {
return 0;
}
}
}public class smallToLarge {
public static void main(String[] args) {
List<String> arrList = new ArrayList<String>();
Scanner o = new Scanner(System.in);
System.out.println("Enter the Sentence : ");
String sentance = o.nextLine().toLowerCase();
String[] str = sentance.split("\\s+");
Arrays.sort(str, new Sorted());
for (int i = 0; i < str.length; i++) {
if (!arrList.contains(str[i])) {
arrList.add(str[i]);
}
}
for (int j = 0; j < arrList.size(); j++) {
System.out.print(arrList.get(j) + " " + arrList.get(j).length() + " ");
}
}
}
【问题讨论】:
-
你试过使用递归吗?
-
不知道如何实现!因为它需要排序并且需要删除重复项。 @Goion 你能帮帮我吗?
-
如果您不想使用数组列表或其他东西,为什么不尝试使用正则表达式之类的东西?
-
@ChathurangaKalana 仅对标准字符串 API 提出了挑战。以及如何使用正则表达式实现?
-
您可以先删除重复项和担心排序