作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址: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

题目大意

把句子中的每个单词用给的字典进行替换,替换时优先替换成最短的词。替换就是找出最短的头部匹配;如果字典中不存在,就保留原来的词。

解题方法

set

看了下给出的Note,发现并没有特别长,普通的方法应该就能搞定,不会超时。

下面的方法叫做Prefix Hash,对于python而言就是用了set的意思。

class Solution(object):
def replaceWords(self, dict, sentence):
"""
:type dict: List[str]
:type sentence: str
:rtype: str
"""
rootset = set(dict)
def replace(word):
for i in xrange(len(word)):
if word[:i] in rootset:
return word[:i]
return word
return ' '.join(map(replace, sentence.split()))

字典

用数组保存dict中,每个小写字符开头的单词。然后对给出的句子进行遍历每个单词,判断这个单词能不能用更短的前缀替换。题目中要求用尽可能短的单词进行替换,所以需要排序,让短的单词在前面。

class Solution {
public:
string replaceWords(vector<string>& dict, string sentence) {
vector<vector<string>> m(26);
sort(dict.begin(), dict.end(), [](string a, string b) {
return a.size() < b.size();});
for (string s : dict)
m[s[0] - 'a'].push_back(s);
istringstream is(sentence);
string cur;
string res;
while (is >> cur) {
for (string word : m[cur[0] - 'a']) {
if (word == cur.substr(0, word.size())) {
cur = word;
break;
}
}
res += cur + ' ';
}
res.pop_back();
return res;
}
};

前缀树

前缀树,又称字典树Trie。具体实现可以看208. Implement Trie (Prefix Tree)

这个题里面,使用了Trie。做法比较简单,把所有的字典前缀放入Trie里面,然后再查句子每个单词是否在里面即可。

需要注意的是,我们的根节点没有存储字符,遍历Trie的时候,p的child数组是我们对应的当前字符。如果当前节点是单词,就直接返回了。如果当前节点不是单词,然后它的child又是空,说明不符合要查找的字符串。就返回掉原始字符串即可。

class TrieNode {
public:
vector<TrieNode*> child;
bool isWord;
TrieNode() : isWord(false), child(26, nullptr){};
~TrieNode() {
for (auto& a : child)
delete a;
}
};
class Solution {
public:
string replaceWords(vector<string>& dict, string sentence) {
root = new TrieNode();
for (string& d : dict) {
insert(d);
}
istringstream is(sentence);
string res;
string cur;
while (is >> cur) {
res += getPrefix(cur) + ' ';
}
res.pop_back();
return res;
}
string getPrefix(string word) {
TrieNode* p = root;
string path;
for (char& c : word) {
int i = c - 'a';
if (p->isWord)
return path;
if (!p->child[i])
return word;
path += c;
p = p->child[i];
}
return word;
}
void insert(string word) {
TrieNode* p = root;
for (char& c : word) {
int i = c - 'a';
if (!p->child[i])
p->child[i] = new TrieNode();
p = p->child[i];
}
p->isWord = true;
}
private:
TrieNode* root;
};

日期

2018 年 2 月 27 日
2018 年 12 月 18 日 —— 改革开放40周年

【LeetCode】648. Replace Words 解题报告(Python & C++)的更多相关文章

  1. 【LeetCode】120. Triangle 解题报告(Python)

    [LeetCode]120. Triangle 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址htt ...

  2. LeetCode 1 Two Sum 解题报告

    LeetCode 1 Two Sum 解题报告 偶然间听见leetcode这个平台,这里面题量也不是很多200多题,打算平时有空在研究生期间就刷完,跟跟多的练习算法的人进行交流思想,一定的ACM算法积 ...

  3. 【LeetCode】Permutations II 解题报告

    [题目] Given a collection of numbers that might contain duplicates, return all possible unique permuta ...

  4. 【LeetCode】Island Perimeter 解题报告

    [LeetCode]Island Perimeter 解题报告 [LeetCode] https://leetcode.com/problems/island-perimeter/ Total Acc ...

  5. 【LeetCode】01 Matrix 解题报告

    [LeetCode]01 Matrix 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/01-matrix/#/descripti ...

  6. 【LeetCode】Largest Number 解题报告

    [LeetCode]Largest Number 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/largest-number/# ...

  7. 【LeetCode】Gas Station 解题报告

    [LeetCode]Gas Station 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/gas-station/#/descr ...

  8. LeetCode: Unique Paths II 解题报告

    Unique Paths II Total Accepted: 31019 Total Submissions: 110866My Submissions Question Solution  Fol ...

  9. Leetcode 115 Distinct Subsequences 解题报告

    Distinct Subsequences Total Accepted: 38466 Total Submissions: 143567My Submissions Question Solutio ...

随机推荐

  1. ZAQI

    mysql> CREATE TABLE emploee ( -> name CHAR(64) NOT NULL, -> email CHAR(64), -> password ...

  2. Excel-计算年龄、工龄 datedif()

    函数名称:DATEDIF 主要功能:计算返回两个日期参数的差值. 使用格式:=DATEDIF(date1,date2,"y").=DATEDIF(date1,date2," ...

  3. 非标准的xml解析器的C++实现:一、思考基本数据结构的设计

    前言: 我在C++项目中使用xml作为本地简易数据管理,到目前为止有5年时间了,从最初的全文搜索标签首尾,直到目前项目中实际运用的类库细致到已经基本符合w3c标准,我一共写过3次解析器,我自己并没有多 ...

  4. Rational Rose的安装及使用教程(包括菜单命令解释、操作向导说明、快捷命令说明)

    一.安装教程 我安装时用的是镜像文件,所以安装前需要辅助软件来处理镜像文件.我用到的是UltraISO.UltraISO中文名叫软碟通 是一款功能强大而又方便实用的光盘映像文件的制作/编辑/转换工具, ...

  5. day07 ORM中常用字段和参数

    day07 ORM中常用字段和参数 今日内容 常用字段 关联字段 测试环境准备 查询关键字 查看ORM内部SQL语句 神奇的双下划线查询 多表查询前提准备 常用字段 字段类型 AutoField in ...

  6. day11 四层负载均衡和http协议

    day11 四层负载均衡和http协议 四层负载均衡和七层负载均衡的区别 四层和七层负载均衡的区别 四层负载均衡数据包在底层就进行了分发,而七层负载均衡数据包则是在最顶层进行分发.由此可以看出,七层负 ...

  7. Linux学习 - 流程控制

    一.if语句 1 单分支if条件语句 (1) if  [ 条件判断式 ];then 程序  fi (2) if [ 条件判断式 ] then 程序  fi 例:检测根分区的使用量 2 双分支if条件语 ...

  8. 记录一下使用MySQL的left join时,遇到的坑

    # 现象 left join在我们使用mysql查询的过程中可谓非常常见,比如博客里一篇文章有多少条评论.商城里一个货物有多少评论.一条评论有多少个赞等等.但是由于对join.on.where等关键字 ...

  9. implicit declaration of function 'NSFileTypeForHFSTypeCode' is invalid in c99

    问题:implicit declaration of function 'NSFileTypeForHFSTypeCode' is invalid in c99 解决办法: 在出现该问题的函数前后加上 ...

  10. awk统计命令(求和、求平均、求最大值、求最小值)

    本节内容:awk统计命令 1.求和 cat data|awk '{sum+=$1} END {print "Sum = ", sum}' 2.求平均 cat data|awk '{ ...