Untitled
unknown
plain_text
a year ago
2.8 kB
5
Indexable
Never
import java.util.*; class UserSolution { HashMap<String, Word> hmW = new HashMap<>(); Trie root; int time; void init() { hmW.clear(); root = new Trie(); time = 0; } void inputWord(char[] mWord) { time++; String str = convertChar2Str(mWord); Word word = hmW.get(str); if (word == null) { word = new Word(str, time); hmW.put(str, word); Trie temp = root; for (int i = 0; i < str.length(); i++) { int index = mWord[i] - 'a'; if (temp.node[index] == null) { temp.node[index] = new Trie(); } temp = temp.node[index]; temp.list.add(word); } } else { if (word.count == 0) return; word.count++; word.fre = time; } } int recommend(char[] mUser, char[] mAnswer) { String str = convertChar2Str(mUser); Trie temp = root; for (int i = 0; i < str.length(); i++) { int index = mUser[i] - 'a'; if (temp.node[index] == null) { outPut(str, mAnswer); return str.length(); } temp = temp.node[index]; } String res = temp.findWord(str); outPut(res, mAnswer); return res.length(); } void outPut(String str, char[] mAnswer) { int i = 0; for (; i < str.length(); i++) { mAnswer[i] = str.charAt(i); } mAnswer[i] = '\0'; } void banWord(char[] mWord) { String str = convertChar2Str(mWord); Word word = hmW.get(str); if (word != null) { word.count = 0; } else { word = new Word(str, time); word.count = 0; hmW.put(str, word); } } private String convertChar2Str(char[] path) { int index = 0; while (path[index] != '\0') { index++; } return String.copyValueOf(path, 0, index); } } class Word{ String str; int count; int fre; public Word(String str, int fre) { this.str = str; count = 1; this.fre = fre; } } class Trie { ArrayList<Word> list = new ArrayList<Word>(); Trie[] node = new Trie[26]; String findWord(String str) { Word res = new Word(str, 9999999); res.count = 0; for (Word word: list) { if (word.count > res.count || (word.count == res.count && word.fre > res.fre)) { res = word; } } return res.str; } }