classSolution: defreplaceWords(self, dictionary: List[str], sentence: str) -> str: dictionarySet = set(dictionary) words = sentence.split(' ') for i, word inenumerate(words): for j inrange(1, len(words) + 1): if word[:j] in dictionarySet: words[i] = word[:j] break return' '.join(words)
[sol1-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution { public String replaceWords(List<String> dictionary, String sentence) { Set<String> dictionarySet = newHashSet<String>(); for (String root : dictionary) { dictionarySet.add(root); } String[] words = sentence.split(" "); for (inti=0; i < words.length; i++) { Stringword= words[i]; for (intj=0; j < word.length(); j++) { if (dictionarySet.contains(word.substring(0, 1 + j))) { words[i] = word.substring(0, 1 + j); break; } } } return String.join(" ", words); } }
[sol1-C#]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
publicclassSolution { publicstringReplaceWords(IList<string> dictionary, string sentence) { ISet<string> dictionarySet = new HashSet<string>(); foreach (string root in dictionary) { dictionarySet.Add(root); } string[] words = sentence.Split(" "); for (int i = 0; i < words.Length; i++) { string word = words[i]; for (int j = 0; j < word.Length; j++) { if (dictionarySet.Contains(word.Substring(0, 1 + j))) { words[i] = word.Substring(0, 1 + j); break; } } } return String.Join(" ", words); } }
char ** split(char *str, char ch, int *returnSize) { int len = strlen(str); char **res = (char **)malloc(sizeof(char *) * len); int i = 0, pos = 0; while (i < len) { while (i < len && str[i] == ch) { i++; } int start = i; while (i < len && str[i] != ch) { i++; } if (start < len) { res[pos] = (char *)malloc(sizeof(char) * (i - start + 1)); memcpy(res[pos], str + start, sizeof(char) * (i - start)); res[pos][i - start] = '\0'; pos++; } } *returnSize = pos; return res; }
char * replaceWords(char ** dictionary, int dictionarySize, char * sentence){ HashItem *dictionarySet = NULL; for (int i = 0; i < dictionarySize; i++) { HashItem *pEntry = (HashItem *)malloc(sizeof(HashItem)); pEntry->key = dictionary[i]; HASH_ADD_STR(dictionarySet, key, pEntry); } int n = strlen(sentence); int wordsSize = 0; char **words = split(sentence, ' ', &wordsSize); char str[MAX_STR_LEN]; for (int i = 0; i < wordsSize; i++) { int len = strlen(words[i]); for (int j = 0; j < len; j++) { snprintf(str, j + 2, "%s", words[i]); HashItem *pEntry = NULL; HASH_FIND_STR(dictionarySet, str, pEntry); if (pEntry) { words[i][j + 1] = '\0'; break; } } } char *res = (char *)malloc(sizeof(char) * (n + 1)); int pos = 0; for (int i = 0; i < wordsSize - 1; i++) { pos += sprintf(res + pos, "%s ", words[i]); } pos += sprintf(res + pos, "%s", words[wordsSize - 1]); for (int i = 0; i < wordsSize; i++) { free(words[i]); } HashItem *curr = NULL, *tmp = NULL; HASH_ITER(hh, dictionarySet, curr, tmp) { HASH_DEL(dictionarySet, curr); free(curr); } return res; }
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
funcreplaceWords(dictionary []string, sentence string)string { dictionarySet := map[string]bool{} for _, s := range dictionary { dictionarySet[s] = true } words := strings.Split(sentence, " ") for i, word := range words { for j := 1; j <= len(word); j++ { if dictionarySet[word[:j]] { words[i] = word[:j] break } } } return strings.Join(words, " ") }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
var replaceWords = function(dictionary, sentence) { const dictionarySet = newSet(); for (const root of dictionary) { dictionarySet.add(root); } const words = sentence.split(" "); for (let i = 0; i < words.length; i++) { const word = words[i]; for (let j = 0; j < word.length; j++) { if (dictionarySet.has(word.substring(0, 1 + j))) { words[i] = word.substring(0, 1 + j); break; } } } return words.join(' '); };
复杂度分析
时间复杂度:O(d + \sum w_i^2)。其中 d 是 dictionary 的字符数,构建哈希集合消耗 O(d) 时间。w_i 是 sentence 分割后第 i 个单词的字符数,判断单词的前缀子字符串是否位于哈希集合中消耗 O(w_i^2) 时间。
classSolution: defreplaceWords(self, dictionary: List[str], sentence: str) -> str: trie = {} for word in dictionary: cur = trie for c in word: if c notin cur: cur[c] = {} cur = cur[c] cur['#'] = {}
words = sentence.split(' ') for i, word inenumerate(words): cur = trie for j, c inenumerate(word): if'#'in cur: words[i] = word[:j] break if c notin cur: break cur = cur[c] return' '.join(words)
publicclassSolution { publicstringReplaceWords(IList<string> dictionary, string sentence) { Trie trie = new Trie(); foreach (string word in dictionary) { Trie cur = trie; for (int i = 0; i < word.Length; i++) { char c = word[i]; if (!cur.Children.ContainsKey(c)) { cur.Children.Add(c, new Trie()); } cur = cur.Children[c]; } cur.Children.Add('#', new Trie()); } string[] words = sentence.Split(" "); for (int i = 0; i < words.Length; i++) { words[i] = FindRoot(words[i], trie); } returnstring.Join(" ", words); }
publicstringFindRoot(string word, Trie trie) { StringBuilder root = new StringBuilder(); Trie cur = trie; for (int i = 0; i < word.Length; i++) { char c = word[i]; if (cur.Children.ContainsKey('#')) { return root.ToString(); } if (!cur.Children.ContainsKey(c)) { return word; } root.Append(c); cur = cur.Children[c]; } return root.ToString(); } }
publicclassTrie { public Dictionary<char, Trie> Children;
publicTrie() { Children = new Dictionary<char, Trie>(); } }
funcreplaceWords(dictionary []string, sentence string)string { type trie map[rune]trie root := trie{} for _, s := range dictionary { cur := root for _, c := range s { if cur[c] == nil { cur[c] = trie{} } cur = cur[c] } cur['#'] = trie{} }
words := strings.Split(sentence, " ") for i, word := range words { cur := root for j, c := range word { if cur['#'] != nil { words[i] = word[:j] break } if cur[c] == nil { break } cur = cur[c] } } return strings.Join(words, " ") }
var replaceWords = function(dictionary, sentence) { const trie = newTrie(); for (const word of dictionary) { let cur = trie; for (let i = 0; i < word.length; i++) { const c = word[i]; if (!cur.children.has(c)) { cur.children.set(c, newTrie()); } cur = cur.children.get(c); } cur.children.set('#', newTrie()); } const words = sentence.split(" "); for (let i = 0; i < words.length; i++) { words[i] = findRoot(words[i], trie); } return words.join(" "); };
constfindRoot = (word, trie) => { let root = ''; let cur = trie; for (let i = 0; i < word.length; i++) { const c = word[i]; if (cur.children.has('#')) { return root; } if (!cur.children.has(c)) { return word; } root += c; cur = cur.children.get(c); } return root; }