LeetCode Replace Words
原题链接在这里:https://leetcode.com/problems/replace-words/description/
题目:
In English, we have a concept called root, which can be followed by some other words to form another longer word - let's call this word successor. For example, the root an, followed by other, which can form another word another.
Now, given a dictionary consisting of many roots and a sentence. You need to replace all the successor in the sentence with the root forming it. If a successor has many roots can form it, replace it with the root with the shortest length.
You need to output the sentence after the replacement.
Example 1:
Input: dict = ["cat", "bat", "rat"]
sentence = "the cattle was rattled by the battery"
Output: "the cat was rat by the bat"
Note:
- The input will only have lower-case letters.
- 1 <= dict words number <= 1000
- 1 <= sentence words number <= 1000
- 1 <= root length <= 100
- 1 <= sentence words length <= 1000
题解:
利用Trie树. 把dict中每个词先放进Trie树中.
对于sentence按照空格拆分出的token, 从头添加token的char, 试验是否能在Trie树中找到. 找到说明加到这就是个root了, 可以返回.
若是Trie树中都没有starts with当前值时说明这个token 没有root, 返回原token.
Time Complexity: O(n*m + k*p). n = dict.size(). m是dict中单词平均长度. k是sentence中token个数. p是token平均长度.
Space: O(n*m+k).
AC Java:
class Solution {
public String replaceWords(List<String> dict, String sentence) {
if(sentence == null || sentence.length() == 0 || dict == null || dict.size() == 0){
return sentence;
}
Trie trie = new Trie();
for(String word : dict){
trie.insert(word);
}
String [] tokens = sentence.split("\\s+");
StringBuilder sb = new StringBuilder();
for(String token : tokens){
sb.append(getRootOrDefault(token, trie) + " ");
}
sb.deleteCharAt(sb.length()-1);
return sb.toString();
}
private String getRootOrDefault(String s, Trie trie){
StringBuilder sb = new StringBuilder();
for(int i = 0; i<s.length(); i++){
sb.append(s.charAt(i));
if(trie.search(sb.toString())){
return sb.toString();
}else if(!trie.startsWith(sb.toString())){
return s;
}
}
return s;
}
}
class Trie{
private TrieNode root;
public Trie(){
root = new TrieNode();
}
public void insert(String word){
TrieNode p = root;
for(char c : word.toCharArray()){
if(p.nexts[c-'a'] == null){
p.nexts[c-'a'] = new TrieNode();
}
p = p.nexts[c-'a'];
}
p.val = word;
}
public boolean search(String word){
TrieNode p = root;
for(char c : word.toCharArray()){
if(p.nexts[c-'a'] == null){
return false;
}
p = p.nexts[c-'a'];
}
return p.val.equals(word);
}
public boolean startsWith(String word){
TrieNode p = root;
for(char c : word.toCharArray()){
if(p.nexts[c-'a'] == null){
return false;
}
p = p.nexts[c-'a'];
}
return true;
}
}
class TrieNode{
String val = "";
TrieNode [] nexts;
public TrieNode(){
nexts = new TrieNode[26];
}
}
Another implementation.
class Solution {
public String replaceWords(List<String> dict, String sentence) {
if(sentence == null || sentence.length() == 0 || dict == null || dict.size() == 0){
return sentence;
}
TrieNode root = new TrieNode();
for(String word : dict){
TrieNode p = root;
for(char c : word.toCharArray()){
if(p.nexts[c-'a'] == null){
p.nexts[c-'a'] = new TrieNode();
}
p = p.nexts[c-'a'];
}
p.val = word;
}
String [] words = sentence.split("\\s+");
for(int i = 0; i<words.length; i++){
TrieNode p = root;
for(char c : words[i].toCharArray()){
if(p.nexts[c-'a'] == null || p.val != null){
break;
}
p = p.nexts[c-'a'];
}
words[i] = (p.val == null) ? words[i] : p.val;
}
return String.join(" ", words);
}
}
class TrieNode{
String val;
TrieNode [] nexts;
public TrieNode(){
nexts = new TrieNode[26];
}
}
LeetCode Replace Words的更多相关文章
- [LeetCode] Replace Words 替换单词
In English, we have a concept called root, which can be followed by some other words to form another ...
- [LeetCode] Find And Replace in String 在字符串中查找和替换
To some string S, we will perform some replacement operations that replace groups of letters with ne ...
- LeetCode 1234. Replace the Substring for Balanced String
原题链接在这里:https://leetcode.com/problems/replace-the-substring-for-balanced-string/ 题目: You are given a ...
- 【LeetCode】648. Replace Words 解题报告(Python & C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 set 字典 前缀树 日期 题目地址:https:/ ...
- 【LeetCode】833. Find And Replace in String 解题报告(Python)
[LeetCode]833. Find And Replace in String 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu ...
- LeetCode 648. Replace Words (单词替换)
题目标签:HashMap 题目给了我们一个array 的 root, 让我们把sentence 里面得每一个word 去掉它得 successor. 把每一个root 存入hash set,然后遍历s ...
- [LeetCode] 890. Find and Replace Pattern 查找和替换模式
You have a list of words and a pattern, and you want to know which words in words matches the patter ...
- Leetcode: Find And Replace in String
To some string S, we will perform some replacement operations that replace groups of letters with ne ...
- 【leetcode】1234. Replace the Substring for Balanced String
题目如下: You are given a string containing only 4 kinds of characters 'Q', 'W', 'E' and 'R'. A string i ...
随机推荐
- HTML5/CSS3鼠标悬停动画菜单按钮
在线演示 本地下载
- error C2665: “std::locale::facet::operator new”: 2 个重载中没有一个可以转换所有参数类型
qt项目 qt creator项目由插件自动转换成的vs2015项目,为了发布少带些dll ,切换成vs2013项目,在更改了一些vs2013不支持的c++新标准写法之后,release可正常编过,但 ...
- 多线程、多进程、协程、IO多路复用请求百度
最近学习了多线程.多进程.协程以及IO多路复用,那么对于爬取数据来说,这几个方式哪个最快呢,今天就来稍微测试一下 普通方式请求百度5次 import socket import time import ...
- javascript-电话薄小功能
上代码: <style> *{ margin:0 ; padding: 0;} .phrase_wrap, .phrase_list{ width: 200px; height: 200p ...
- 尽可能的构建一个拓展性比"较好"的项目,会让你后期迭代好受点
转载请注明出处:王亟亟的大牛之路 这礼拜基本都在忙自己项目上的事,然后之后会"重新整理"后把这部分的功能开源出来,这里@下队友 NeglectedByBoss 本周还是没有停更收纳 ...
- SpringMVC下文件的上传与下载以及文件列表的显示
1.配置好SpringMVC环境-----SpringMVC的HelloWorld快速入门! 导入jar包:commons-fileupload-1.3.1.jar和commons-io-2.4.ja ...
- lua笔记之userdata
1.一直使用框架里封装好的c库,想着自己一点一点的写些例子,学习下,以后需要c库,可以自己写了. 下边是一个简单的userdata的例子--数组操作. newarray.c #include &quo ...
- Eclipse工具栏上android的机器人小图标不见了
可以通过「Window」⇒「Customize Perspective」⇒「Tool Bar Visibility」Tab画面上选择Android SDK and AVD Manager来显示
- MyEclipse安装git插件
安装egit插件的步骤(安装egit不成功的原因主要是下载的egit版本不适合当前使用的eclipse版本).先检查自己MyEclipse适用egit的版本. 查看自己MyEclipse版本,如下图: ...
- 【Demo】CSS图像拼合技术
图像拼合 图像拼合 - 简单实例 <style> img.home { width: 46px; height: 44px; background: url(/images/img_nav ...