【发布时间】:2014-01-31 15:53:24
【问题描述】:
我编写了一个算法,可以在字典中搜索一个单词。但它只搜索指定长度单词的 1 或 2 个字母。
Ex 搜索:-
一个**
结果应该是:-
帮助,瞄准,
我使用线性搜索算法来查找符合我的条件的单词。但我想知道是否可以使用二进制搜索代替线性搜索?如果是这样,那么任何人都可以给我一些提示
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Cse221LabAssignment1 {
/**
* @param args the command line arguments
*/
public static final String wordListFileName = "E:\\BRAC UNI\\cse lab\\cse221 lab\\cse221LabAssignment1\\src\\cse221labassignment1\\WordList.txt";
public static final String searchListFileName = "E:\\BRAC UNI\\cse lab\\cse221 lab\\cse221LabAssignment1\\src\\cse221labassignment1\\SearchList.txt";
public static void main(String[] args) {
// TODO code application logic here
String wordList, searchList;
wordList = ReadFile(wordListFileName); //Reading wordlist
searchList = ReadFile(searchListFileName); //Reading searchList
String[] w = wordList.split("\\,"); //Spliting wordlist and putting it into an array
String[] s = searchList.split("\\,"); //Spliting searchList and putting it into an array
for (int c = 0; c < s.length; c++) { //iterating through the searchList array
// String [] refinedList=new String[w.length]; //array containing the list of words that matches with the lenght of search word.
// int refinedCounter=0; //counter for the refinedList array
for (int i = 0; i < w.length; i++) { //iterating through the wordList array
if (s[c].length() == w[i].length()) {
// refinedList[refinedCounter]=w[i];
// refinedCounter++;
if (LetterMatch(w[i], s[c])) {
System.out.print(w[i]);
if (i < w.length - 1) {
System.out.print(",");
} else {
System.out.println(";");
}
}
}
}
}
}
public static String ReadFile(String fileName) {
Scanner k = null;
try {
k = new Scanner(new File(fileName));
} catch (FileNotFoundException ex) {
System.out.println(ex);
}
String rt = k.nextLine();
while (k.hasNextLine()) {
rt = rt + "," + k.nextLine(); //Words seperated by Comma
}
return rt;
}
public static boolean LetterMatch(String m, String s) {
char[] letters = m.toCharArray();
char[] searchLetters = s.toCharArray();
boolean match = false;
int c = 0;
for (; c < s.length(); c++) {
if (searchLetters[c] != '*') {
if (searchLetters[c] == letters[c]) {
match = true;
} else {
match = false;
}
}
}
if (c != s.length()) {
return false;
} else {
return match;
}
}
}
【问题讨论】:
-
维基百科在这里有很好的描述:en.wikipedia.org/wiki/Binary_search_algorithm#Word_lists
标签: java algorithm search dictionary binary-search