67,513
社区成员
发帖
与我相关
我的任务
分享
public class TextCompare {
public static void main(String[] args) throws Exception {
minus("nnice", "nmice");
minus("nmice", "nnice");
minus("nmice", "nrice");
minus("rrice", "nnice");
minus("naice", "mdice");
}
public static List<Character> minus(String base, String minus) {
List<Character> cb = toChars(base);
List<Character> cm = toChars(minus);
List<Character> ret = minus(cb, cm);
System.out.println(ret);
return ret;
}
private static List<Character> minus(List<Character> base, List<Character> minus) {
List<Character> ret = new ArrayList<Character>();
ret.addAll(base);
for (Character c : minus) {
for (int i = 0; i < ret.size(); i++) {
if (ret.get(i).equals(c)) {
ret.remove(i);
break;
}
}
}
return ret;
}
private static List<Character> toChars(String str) {
List<Character> ret = new ArrayList<Character>();
char[] cs = str.toCharArray();
for (char c : cs) {
ret.add(c);
}
return ret;
}
}
public class TextCompare {
public static void main(String[] args) throws Exception {
Dict dict = new Dict("dict.txt");
System.out.println("hello: " + dict.contains("hello"));
System.out.println("nice: " + dict.contains("nice"));
}
}
/**
* 字典:构造行数中传入字典文件的路径和名称。
*/
class Dict {
private HashSet<String> hsDict = new HashSet<String>();
public Dict(String dictFileName) throws Exception {
Scanner sc = null;
try {
// 定位字典文件
File f = new File(dictFileName);
if (f.exists()) {
sc = new Scanner(f);
} else {
sc = new Scanner(this.getClass().getResourceAsStream(dictFileName));
}
// 开始装载字典文件中的所有单词
long timer = System.currentTimeMillis();
while (sc.hasNext()) {
hsDict.add(sc.next());
}
timer = System.currentTimeMillis() - timer;
System.out.println("Dict inited, spend: " + timer + "ms, get words: " + hsDict.size());
} finally {
if (sc != null) {
sc.close();
}
}
}
public boolean contains(String word) {
return hsDict.contains(word);
}
}