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 ...
随机推荐
- python 异常的引发和捕捉处理
1.什么是异常(exception): 异常是python发现某个地方出现逻辑错误时,抛出一个信号,即异常的引发.如果有捕捉语句在,则异常信号被捕捉,如果没有则会传递到默认异常处理器(终止程序). ...
- APPIUM API整理(python)---操作类
前言:android手机大家都很熟悉,操作有按键.触摸.点击.滑动等,各种操作方法可以通过api的方法来实现. 参考博文:http://blog.csdn.net/bear_w/article/det ...
- Kali Linux学习笔记
1. 重装grub 重装windows后MBR被覆盖导致linux无法启动,通过U盘进入live后执行以下命令: mount /dev/sda5 /mnt //此处是将linux系统根目录挂载到mnt ...
- 2 Powershell与Cmd以及Unix/Linux Shell
上篇文章我说道,windows为了改变用户对其console界面的诟病,于是就从windows vista开始,计划要改变这种局面,于是就有 了Powershell的出现. 1.兼容shell命令 ...
- JS复制内容到剪贴板: 兼容IE、Firefox、Chrome、Safari所有浏览器【转】
正 文: 现在浏览器种类也越来越多,诸如 IE.Firefox.Chrome.Safari等等,因此现在要实现一个js复制内容到剪贴板的小功能就不是一件那么容易的事了. 在FLASH 9 时代,有一个 ...
- springmvc跨域
//mvc默认是text/plain;charset=ISO-8859-1@RequestMapping(value = "/xxx", produces = "appl ...
- 开发中Dialog多弹窗管理
随着项目的不断迭代,加上产品经理大法(这里加一个弹窗提示,这里加一个引导….)各种弹窗在应用启动时候需要展示, 然而它们出现的时机还有可能重叠.我勒个擦...有没有一种优(tou)雅(lan)的方式来 ...
- 找出此产品描述中包含N个关键字的长度最短的子串
阿里巴巴笔试题:给定一段产品的英文描述,包含M个英文字母,每个英文单词以空格分隔,无其他标点符号:再给定N个英文关键词,请说明思路并变成实现方法. String extractSummary(Stri ...
- Dubbo定义及其作用
Dubbo定义 Dubbo是一个分布式服务框架,致力于提供高性能和透明化的RPC远程服务调用方案,以及SOA服务治理方案.简单的说,dubbo就是个服务框架,如果没有分布式的需求,其实是不需要用的,只 ...
- 最详细的虚拟机安装centos7教程
参考网站:https://jingyan.baidu.com/article/b7001fe1d1d8380e7382dd72.html 安装vmware10,vmware是收费的,作为学习,我介意还 ...