/
BasicSpellChecker.java
52 lines (41 loc) · 2.1 KB
/
BasicSpellChecker.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package com.interview.array;
import java.io.*;
import java.util.*;
import java.util.regex.*;
public class BasicSpellChecker {
private final HashMap<String, Integer> nWords = new HashMap<String, Integer>();
public BasicSpellChecker(String file) throws IOException {
BufferedReader in = new BufferedReader(new FileReader(file));
Pattern p = Pattern.compile("\\w+");
for(String temp = ""; temp != null; temp = in.readLine()){
Matcher m = p.matcher(temp.toLowerCase());
while(m.find())
nWords.put((temp = m.group()), nWords.containsKey(temp) ? nWords.get(temp) + 1 : 1);
}
in.close();
}
private final ArrayList<String> edits(String word) {
ArrayList<String> result = new ArrayList<String>();
for(int i=0; i < word.length(); ++i) result.add(word.substring(0, i) + word.substring(i+1));//deletes
for(int i=0; i < word.length()-1; ++i) result.add(word.substring(0, i) + word.substring(i+1, i+2) + word.substring(i, i+1) + word.substring(i+2));//swaps
for(int i=0; i < word.length(); ++i) for(char c='a'; c <= 'z'; ++c) result.add(word.substring(0, i) + String.valueOf(c) + word.substring(i+1));//replace
for(int i=0; i <= word.length(); ++i) for(char c='a'; c <= 'z'; ++c) result.add(word.substring(0, i) + String.valueOf(c) + word.substring(i));//inserts
return result;
}
public final String correct(String word) {
if(nWords.containsKey(word)) return word;
ArrayList<String> list = edits(word);
HashMap<Integer, String> candidates = new HashMap<Integer, String>();
for(String s : list) if(nWords.containsKey(s)) candidates.put(nWords.get(s),s);
if(candidates.size() > 0) return candidates.get(Collections.max(candidates.keySet()));
return candidates.size() > 0 ? candidates.get(Collections.max(candidates.keySet())) : word;
}
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
BasicSpellChecker spell = new BasicSpellChecker("C:\\Users\\Shivankur Kapoor\\Desktop\\corpus.txt");
while(T-->0){
System.out.println((spell.correct(br.readLine())));
}
}
}