package spell; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.ListIterator; /** * 1、創建一個List集合存儲字典集 * 2、創建一個List集合存儲需要檢查的集合 * 3、將需要檢查的集合與字典集合進行比對,通過刪除,替換,插入等操作確定是否是字典集的字 * 是則輸出XX is correct不是則進行比對輸出,字典中不存在則輸出空 * @author AbuGe * */ public class SpellChecker { public static void main(String[] args) throws IOException { //創建一個字典集和 ListdictionaryList = new ArrayList (); //創建一個輸入字典集 List inputList = new ArrayList (); //設置#的開始與結束標記 boolean startFlag = false; boolean endFlag = false; //設置一個統計#個數的標記 int count = 0; //輸入一行數據 InputStream in = System.in; InputStreamReader isr = new InputStreamReader(in); BufferedReader bufr = new BufferedReader(isr); String line = null; while(!startFlag || !endFlag) { line = bufr.readLine(); if(line.equals("#")) { count++; } if(count == 1 && !startFlag) { startFlag = true; continue; } if(count == 2) { endFlag = true; continue; } if(!startFlag) { dictionaryList.add(line); } if(startFlag) { inputList.add(line); } } //待檢查的List集合的迭代器 ListIterator inputIterator = inputList.listIterator(); while(inputIterator.hasNext()) { String input = inputIterator.next(); StringBuilder sb = new StringBuilder(); if(dictionaryList.contains(input)) { System.out.println(input + " is correct"); }else { ListIterator dictionaryIterator = dictionaryList.listIterator(); char[] inputTemp = input.toCharArray(); sb.append(input); sb.append(":"); while(dictionaryIterator.hasNext()) { String dictionary = dictionaryIterator.next(); char[] dictionaryTemp = dictionary.toCharArray(); boolean replaceFlag = replace(inputTemp, dictionaryTemp); boolean deleteFlag = delete(inputTemp, dictionaryTemp); boolean addFlag = add(inputTemp, dictionaryTemp); if(replaceFlag || deleteFlag || addFlag) { sb.append(" "); sb.append(dictionary); } } String result = sb.toString(); System.out.println(result); } } } //1、替代一位 public static boolean replace(char[] input, char[] dictionary) { //統計不同的字母數 int dif = 0; if(input.length == dictionary.length) { for(int i = 0, j = 0; i < input.length;) { if(input[i++] != dictionary[j++]) dif++; } if(dif > 1) return false; return true; }else { return false; } } //2、刪除一位 public static boolean delete(char[] input, char[] dictionary) { int dif = 0; if(input.length - dictionary.length == 1) { for(int i = 0, j = 0; i < input.length && j < dictionary.length;) { if(input[i] != dictionary[j]) { i++; dif++; if(dif > 1) return false; }else { i++; j++; } } return true; }else { return false; } } //3、添加一位 public static boolean add(char[] input, char[] dictionary) { int dif = 0; if(dictionary.length - input.length == 1) { for(int i = 0, j = 0; j < dictionary.length && i < input.length;) { if(input[i] != dictionary[j]) { dif++; j++; if(dif > 1) { return false; } }else { i++; j++; } } return true; }else { return false; } } }