原题链接在这里: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:

  1. The input will only have lower-case letters.
  2. 1 <= dict words number <= 1000
  3. 1 <= sentence words number <= 1000
  4. 1 <= root length <= 100
  5. 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的更多相关文章

  1. [LeetCode] Replace Words 替换单词

    In English, we have a concept called root, which can be followed by some other words to form another ...

  2. [LeetCode] Find And Replace in String 在字符串中查找和替换

    To some string S, we will perform some replacement operations that replace groups of letters with ne ...

  3. LeetCode 1234. Replace the Substring for Balanced String

    原题链接在这里:https://leetcode.com/problems/replace-the-substring-for-balanced-string/ 题目: You are given a ...

  4. 【LeetCode】648. Replace Words 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 set 字典 前缀树 日期 题目地址:https:/ ...

  5. 【LeetCode】833. Find And Replace in String 解题报告(Python)

    [LeetCode]833. Find And Replace in String 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu ...

  6. LeetCode 648. Replace Words (单词替换)

    题目标签:HashMap 题目给了我们一个array 的 root, 让我们把sentence 里面得每一个word 去掉它得 successor. 把每一个root 存入hash set,然后遍历s ...

  7. [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 ...

  8. Leetcode: Find And Replace in String

    To some string S, we will perform some replacement operations that replace groups of letters with ne ...

  9. 【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 ...

随机推荐

  1. 阿里云服务器: centos7 ftp安装

    阿里云服务器: centos7 ftp安装 ftp需要您参考下面链接和附件开放安全组20.21.1024-65535 后查看是否正常. 配置步骤如下, 1, 如果没有安装ftp,需要先安装 yum - ...

  2. c++中小项堆声明和使用

    c++默认是大顶堆,小顶堆有两种声明方法: 1.对于基本类型直接用 priority_queue<int, vector<int>, greater<int> >p ...

  3. RBAC权限控制

    1.什么是RBAC权限模型rity2.RBAC权限模型表设计3.整合Mybatis数据库4.UserDetailsService5.动态查询数据库登陆6.动态权限角色拦截 什么是RBAC权限模型r 基 ...

  4. JNIjw03

    1.VC6(CPP)的DLL代码: #include<stdio.h> #include "jniZ_JNIjw03.h" JNIEXPORT void JNICALL ...

  5. 入门教程:.NET开源OpenID Connect 和OAuth解决方案IdentityServer v3 创建简单的OAuth2.0服务器,客户端和API(三)

    本教程的目的在于创造尽可能简单的identityserver安装作为一个oauth2授权服务器.这应该能够让你了解一些基本功能和配置选项(完整的源代码可以发现在这里).在后面的文档中会介绍更多的高级功 ...

  6. koa2使用&&中间件&&angular2的koa托管

    文章导航 1,koa2使用: 2,写中间件: 3,koa2路由配置angular2; 一.先上代码,一篇,看完koa2中大多基础方法: const Koa=require('koa'); const ...

  7. linux配置静态ip,关闭防火墙

    在vmware下安装centos6.5通过桥接方式访问外网,因此需要配置ip. 一.ip配置 1.1. 配置动态ip vi /etc/sysconfig/network-scripts/ifcfg-e ...

  8. spring3: AOP 之 通知顺序

    如果我们有多个通知想要在同一连接点执行,那执行顺序如何确定呢?Spring AOP使用AspectJ的优先级规则来确定通知执行顺序.总共有两种情况:同一切面中通知执行顺序.不同切面中的通知执行顺序. ...

  9. python 爬虫004-使用urllib2与正则表达式扒取糗事百科新鲜页首页帖子

    面向过程的方式 #!/usr/bin/env python # -*- coding: utf-8 -*- import urllib2 import sys import re import os ...

  10. 【Demo】CSS3 3D转换

    3D转换transform rotateX() 方法 rotateX()方法,围绕其在一个给定度数X轴旋转的元素. div { transform: rotateX(120deg); -webkit- ...