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:

  1. Input: dict = ["cat", "bat", "rat"]
  2. sentence = "the cattle was rattled by the battery"
  3. Output: "the cat was rat by the bat"
  4.  
  5. 按照题意,基本上能够马上知道这题需要用trie
  1. class Solution {
  2. public String replaceWords(List<String> dict, String sentence) {
  3. String[] tokens = sentence.split(" ");
  4. TrieNode trie = buildTrie(dict);
  5. return replaceWords(tokens, trie);
  6. }
  7.  
  8. private String replaceWords(String[] tokens, TrieNode root) {
  9. StringBuilder stringBuilder = new StringBuilder();
  10. for (String token : tokens) {
  11. stringBuilder.append(getShortestReplacement(token, root));
  12. stringBuilder.append(" ");
  13. }
  14. return stringBuilder.substring(, stringBuilder.length()-);
  15. }
  16.  
  17. private String getShortestReplacement(String token, final TrieNode root) {
  18. TrieNode temp = root;
  19. StringBuilder stringBuilder = new StringBuilder();
  20. for (char c : token.toCharArray()) {
  21. stringBuilder.append(c);
  22. if (temp.map.containsKey(c)) {
  23. if (temp.map.get(c).isWord) {
  24. return stringBuilder.toString();
  25. }
  26. temp = temp.map.get(c);
  27. } else {
  28. return token;
  29. }
  30. }
  31. return token;
  32. }
  33.  
  34. private TrieNode buildTrie(List<String> dict) {
  35. TrieNode root = new TrieNode(' ');
  36. for (String word : dict) {
  37. TrieNode current = root;
  38. for (char ch : word.toCharArray()) {
  39. TrieNode node = current.getChildNode(ch);
  40. if (node == null) {
  41. current.map.put(ch, new TrieNode(ch));
  42. node = current.getChildNode(ch);
  43. }
  44. current = node;
  45. }
  46. current.isWord = true;
  47. }
  48. return root;
  49. }
  50. }
  51.  
  52. class TrieNode {
  53. char ch;
  54. boolean isWord;
  55. Map<Character, TrieNode> map;
  56.  
  57. public TrieNode(char ch) {
  58. this.ch = ch;
  59. map = new HashMap<>();
  60. }
  61.  
  62. public TrieNode getChildNode(char ch) {
  63. return map.get(ch);
  64. }
  65. }

Replace Words的更多相关文章

  1. <JavaScript语言精粹>--<读书笔记三>之replace()与正则

    今天有人问我repalce(),他那个题目很有意思.我也不会做,于是我就去查,结果发现就是最基础的知识的延伸. 所以啊最基础的知识才是很重要的,千万不能忽略,抓起JS就写代码完全不知到所以然,只知道写 ...

  2. StackOverFlow排错翻译 - Python字符串替换: How do I replace everything between two strings without replacing the strings?

    StackOverFlow排错翻译 - Python字符串替换: How do I replace everything between two strings without replacing t ...

  3. js的replace函数入参为function时的疑问

    近期在写js导出excel文件时运用到replace方法,此处详细的记录下它各个参数所代表的的意义. 定义和用法 replace() 方法用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式 ...

  4. ORACLE 利用 REPLACE函数替换字段字符串

    REPLACE(string,s1,s2) string 希望被替换的字符或变量 s1 被替换的字符串 s2 要替换的字符串 SQL> select replace(he love you,he ...

  5. js 页面刷新location.reload和location.replace的区别小结

    reload 方法,该方法强迫浏览器刷新当前页面. 语法: location.reload([bForceGet]) 参数: bForceGet, 可选参数, 默认为 false,从客户端缓存里取当前 ...

  6. replace和translate的用法

    select replace ('111222333444','222','888') from dual;with tmp as(select 'aabb/123\:cde工人' s from du ...

  7. JavaScript replace() 方法

    参考:http://www.w3school.com.cn/jsref/jsref_replace.asp 需要有一点注意的是:可以是函数的形式做为返回值,如下: "test{0}" ...

  8. replace实现正则过滤替换非法字符

    html+js结构如下: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http: ...

  9. Replace 删除、替换函数精解示例

    '************************************************************************* '**模 块 名:Replace函数精解示例 '* ...

  10. angularjs 指令详解 - template, restrict, replace

    通过指令机制,angularjs 提供了一个强大的扩展系统,我们可以通过自定义指令来扩展自己的指令系统. 怎样定义自己的指令呢? 我们通过 Bootstrap UI来学习吧.这个项目使用 angula ...

随机推荐

  1. 【Python之路】特别篇--Bottle

    Bottle Bottle是一个快速.简洁.轻量级的基于WSIG的微型Web框架,此框架只由一个 .py 文件,除了Python的标准库外,其不依赖任何其他模块. Bottle框架大致可以分为以下部分 ...

  2. VirtualBox:启动虚拟机后计算机死机

    造冰箱的大熊猫@cnblogs 2018/2/21 故障描述:Ubuntu 16.04升级Linux内核后,在VirtualBox中启动虚拟机发现Ubuntu死机,只能通过长按电源开关硬关机的方式关闭 ...

  3. MessagePack Java Jackson 在不关闭输出流(output stream)的情况下序列化多变量

    com.fasterxml.jackson.databind.ObjectMapper 在默认的情况下在写出输入后将会关闭输出流(output stream). 如果你希望序列化多值变量在同一个输出流 ...

  4. Fantasy of a Summation (LightOJ - 1213)(快速幂+简单思维)

    题解:根据题目给的程序,就是计算给的这个序列,进行k次到n的循环,每个数需要加的次数是k*n^(k-1),所以快速幂取模,算计一下就可以了. #include <bits/stdc++.h> ...

  5. 【软件工程】Alpha冲刺(3/6)

    链接部分 队名:女生都队 组长博客: 博客链接 作业博客:博客链接 小组内容 恩泽(组长) 过去两天完成了哪些任务 描述 对推送模块进行详细划分 基于用户的协同过滤,寻找更感兴趣的话题 学习API文档 ...

  6. Mac平台最好用的万能开源免费播放器-IINA

    1.安装 1)官网下载地址 https://iina.io/ 2)brew 方式安装 testdeMacBook-Pro:~ test$ brew cask install iina Updating ...

  7. 一、基础篇--1.2Java集合-HashMap死循环问题

    为什么HashMap会出现死循环 首先,我们知道java的HashMap不是线程安全的.多线程下应该使用ConcurrentHashMap. HashMap底层是基于动态数组和单向链表(JDK1.7, ...

  8. LC 856. Score of Parentheses

    Given a balanced parentheses string S, compute the score of the string based on the following rule: ...

  9. C++学习 之 初识头文件

    声明:            本人自学C++, 没有计算机基础,在学习的过程难免会出现理解错误,出现风马牛不相及的现象,甚至有可能会贻笑大方. 如果有幸C++大牛能够扫到本人的博客,诚心希望大牛能给予 ...

  10. 集成学习之Adaboost算法原理

    在boosting系列算法中,Adaboost是最著名的算法之一.Adaboost既可以用作分类,也可以用作回归. 1. boosting算法基本原理 集成学习原理中,boosting系列算法的思想: