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 ...
随机推荐
- MySQL引擎及选择
一.MySQL的存储引擎 完整的引擎说明还是看官方文档:http://dev.mysql.com/doc/refman/5.6/en/storage-engines.html 这里介绍一些主要的引擎 ...
- Spring中Bean管理的常用注解
在Spring中,主要用于管理bean的注解分为四大类:1.用于创建对象.2.用于给对象的属性注入值.3.用于改变作用的范围.4.用于定义生命周期.这几个在开发中经常接触到,也可以说每天都会遇见.其中 ...
- 谷歌浏览器和火狐浏览器设置跨域和https、http混用 Chrome
谷歌浏览器和火狐浏览器设置跨域和https.http混用 Chrome 添加启动项: 右键点击Chrome快捷方式,在目标一栏后添加启动项 允许跨域: --disable-web-securit ...
- JS Object To C# ASP.Net ModelBind
之前做项目的时候发现,Jquery自带的Form 序列化函数.与asp.net 里边的Modelbinding格式不匹配,所以写了一个可以把前端的Object对象序列化成ModelBinding认识的 ...
- python处理数据的风骚操作[pandas 之 groupby&agg]
https://segmentfault.com/a/1190000012394176 介绍 每隔一段时间我都会去学习.回顾一下python中的新函数.新操作.这对于你后面的工作是有一定好处的.本文重 ...
- Spring 静态注入讲解(MethodInvokingFactoryBean)
/* * Copyright (c) 2017 4PX Information Technology Co.,Ltd. All rights reserved. */package com.fpx.o ...
- virtualbox ubuntu下ssh连接
一.首先Ubuntu中安装ssh服务器 Ubuntu 下安装 OpenSSH Server 是无比轻松的一件事情,需要的命令只有一条: sudo apt-get install openssh-ser ...
- Ubuntu 16 安装redis客户端
https://snapcraft.io/redis-desktop-manager sudo snap install redis-desktop-manager 很好用! 支持模糊过滤,两边加星号 ...
- 10 个深恶痛绝的 Java 异常
异常是 Java 程序中经常遇到的问题,我想每一个 Java 程序员都讨厌异常,一 个异常就是一个 BUG,就要花很多时间来定位异常问题. 今天,来列一下 Java 中经常遇到的前 10 个异常,排名 ...
- C# 运行时替换方法(需要unsafe编译)
/* https://stackoverflow.com/questions/7299097/dynamically-replace-the-contents-of-a-c-sharp-method ...