【发布时间】:2017-03-28 21:51:43
【问题描述】:
如何在 Java 中使用二进制搜索来查找用户给出的两个字符串之间有多少个字符串?我有一个大文本文件要搜索。 我在想 ((word position 2 - word position 1)-1) 会给出数组中的位置,但我不太确定如何将它放入代码中。我在检查文件后卡住了。
String[] allWords = new String[400000];
int wordCount = 0;
Scanner input = new Scanner(new File("C:\\text.txt"));
while (input.hasNext()) {
String word = input.next();
allWords[wordCount] = word;
wordCount++;
System.out.println(wordCount);
}
Scanner sc = new Scanner(new File("C:\\text.txt"));
while(sc.hasNextLine()){
String in = sc.nextLine();
System.out.println("Enter a string:");
Scanner sc2 = new Scanner(System.in);
String str = sc2.nextLine();
System.out.println("Enter a string:");
Scanner sc3 = new Scanner(System.in);
String str2 = sc3.nextLine();
if (str.contains(str)) {
System.out.println("yes");
}
if (str.contains(str2)) {
System.out.println("yes");
}
【问题讨论】:
-
我不太明白二分搜索对此的相关性。二进制搜索就是不必搜索整个“树”(按某种顺序排列的元素数组有点像树中的元素)。但是如果你想知道中间有多少东西,那么你必须检查中间的所有元素。我猜可能是对元素进行二进制搜索,然后将其删除/重写为其他内容。然后再次二进制搜索等。虽然我真的不知道。
-
为什么是二分查找?逐行读取文件。查看该行是否等于任一字符串。如果该行等于其中一个字符串,则开始计数,直到找到另一个字符串。
-
所以如果我像在我的代码中那样逐行阅读它,我该如何开始计数?我对编程有点陌生,所以我不确定如何做一些事情,比如从用户那里获取输入并将其放入 if 语句中。
标签: java arrays performance binary-search