648. Replace Words(LeetCode)

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 theroot 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

     1 class Solution {
     2 public:
     3     string replaceWords(vector<string>& dict, string sentence) {
     4         if (sentence.size() == 0 || dict.size() == 0)
     5             return sentence;
     6         stringstream ss(sentence);
     7         vector<string> vet;
     8         string str;
     9         while (ss >> str)
    10         {
    11             vet.push_back(str);
    12         }
    13         for (int i = 0; i < vet.size(); i++)
    14         {
    15             for (int j = 0; j < dict.size(); j++)
    16             {
    17                 /*cout << vet[i] << vet[i].size() << " " << dict[j] << dict[j].size() << "  22" << vet[i].substr(0, dict[j].size()) << endl;*/
    18
    19                 if (vet[i].size() >= dict[j].size() && vet[i].substr(0, dict[j].size()) == dict[j])
    20                 {
    21                             vet[i] = dict[j];
    22                             /*cout <<"11111111"<< vet[i] << endl;*/
    23                 }
    24             }
    25         }
    26         string str1 = "";
    27         for (int i = 0; i < vet.size(); i++)
    28         {
    29             str1 += vet[i];
    30             if (i != vet.size()-1)
    31             str1 += " ";
    32
    33         }
    34         return str1;
    35     }
    36 };

    别人用字典树做的如下:

     1 class Solution {
     2 private:
     3     class TrieNode{
     4         public:
     5         bool eow;
     6         vector<TrieNode*> chars;
     7         TrieNode():eow(false), chars(vector<TrieNode*>(26,NULL)){
     8
     9         }
    10     };
    11
    12     class Trie{
    13         public:
    14         TrieNode* head;
    15
    16         Trie():head(new TrieNode()) {}
    17
    18         bool isWord(string str){
    19            TrieNode* cur = head;
    20             for (int i = 0; i < str.size(); i++){
    21                 char c = str[i];
    22                 int index = (c-‘a‘) %26;
    23                 if (cur->chars[index] == NULL){
    24                     return false;
    25                 }
    26                 cur = cur->chars[index];
    27                 if (index == str.size() - 1){
    28                     return cur->eow;
    29                 }
    30             }
    31         }
    32
    33         void insertWord(string str){
    34             TrieNode* cur = head;
    35             for (int i = 0; i < str.size(); i++){
    36                 char c = str[i];
    37                 int index = (c-‘a‘) %26;
    38                 if (cur->chars[index] == NULL){
    39                     cur->chars[index] = new TrieNode();
    40                 }
    41                 cur = cur->chars[index];
    42                 if (i == str.size() - 1){
    43                     cur->eow = true;
    44                 }
    45             }
    46         }
    47
    48         string getShortestPrefix(string str){
    49             TrieNode* cur = head;
    50             for (int i = 0; i < str.size(); i++){
    51                 char c = str[i];
    52                 int index = (c-‘a‘) %26;
    53                 if (cur->chars[index] == NULL){
    54                     return str;
    55                 }
    56                 if (cur->chars[index]->eow){
    57                     return str.substr(0,i+1);
    58                 }
    59                 cur = cur->chars[index];
    60             }
    61             return str;
    62         }
    63     };
    64 public:
    65     string replaceWords(vector<string>& dict, string sentence) {
    66         Trie trie;
    67         for (string str : dict){
    68             trie.insertWord(str);
    69         }
    70
    71         string ans = "";
    72         int index = 0, beg = 0;
    73         while ((index = sentence.find(‘ ‘,beg)) != string::npos){
    74             ans += trie.getShortestPrefix(sentence.substr(beg, index - beg)) + " ";
    75             beg = index + 1;
    76         }
    77         ans += trie.getShortestPrefix(sentence.substr(beg));
    78         return ans;
    79     }
    80 };
时间: 2024-12-28 01:30:31

648. Replace Words(LeetCode)的相关文章

119. Pascal&#39;s Triangle II(LeetCode)

Given an index k, return the kth row of the Pascal's triangle. For example, given k = 3,Return [1,3,3,1]. Note:Could you optimize your algorithm to use only O(k) extra space? class Solution { public: vector<int> getRow(int rowIndex) { vector<int&

(LeetCode)杨辉三角形Pascal&#39;s Triangle

题目如下: Given numRows, generate the first numRows of Pascal's triangle. For example, given numRows = 5, Return [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] 实现代码如下: public class Solution { public List<List<Integer>> generate(int numRows) { Lis

第15个算法-实现 Trie (前缀树)(LeetCode)

解法代码来源 :https://blog.csdn.net/whdAlive/article/details/81084793 算法来源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/implement-trie-prefix-tree 实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作. 示例: Trie trie = new Trie(); trie.insert("apple"

不邻接植花(leetcode)

有 N 个花园,按从 1 到 N 标记.在每个花园中,你打算种下四种花之一. paths[i] = [x, y] 描述了花园 x 到花园 y 的双向路径. 另外,没有花园有 3 条以上的路径可以进入或者离开. 你需要为每个花园选择一种花,使得通过路径相连的任何两个花园中的花的种类互不相同. 以数组形式返回选择的方案作为答案 answer,其中 answer[i] 为在第 (i+1) 个花园中种植的花的种类.花的种类用  1, 2, 3, 4 表示.保证存在答案. 示例 1: 输入:N = 3,

领扣(LeetCode)二维区域和检索 个人题解

给定一个二维矩阵,计算其子矩形范围内元素的总和,该子矩阵的左上角为 (row1, col1) ,右下角为 (row2, col2). 上图子矩阵左上角 (row1, col1) = (2, 1) ,右下角(row2, col2) = (4, 3),该子矩形内元素的总和为 8. 示例: 给定 matrix = [ [3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5] ] sumRegi

120.三角形最短路径(leetcode)

给定一个三角形,找出自顶向下的最小路径和.每一步只能移动到下一行中相邻的结点上. 法1): 本题典型的回溯算法,但是没有剪枝,在42/43个case的时候超时了,以下是代码. PS:尝试过如果当前和大于全局最小,则停止,但是由于有负数的存在,现在大的值也可以通过-9999成为最小值,剪枝失败. class Solution: def minimumTotal(self, triangle: List[List[int]]) -> int: if not triangle or not trian

树和图(leetcode) : 岛屿数量

给定一个由 '1'(陆地)和 '0'(水)组成的的二维网格,计算岛屿的数量.一个岛被水包围,并且它是通过水平方向或垂直方向上相邻的陆地连接而成的.你可以假设网格的四个边均被水包围. 示例 1: 输入: 11110 11010 11000 00000 输出: 1 示例 2: 输入: 11000 11000 00100 00011 输出: 3 解答(C++): class Solution { public: //广度优先搜索 void dfs(vector<vector<char>>

领扣(LeetCode)独特的电子邮箱地址 个人题解

每封电子邮件都由一个本地名称和一个域名组成,以 @ 符号分隔. 例如,在 [email protected]中, alice 是本地名称,而 leetcode.com 是域名. 除了小写字母,这些电子邮件还可能包含 ',' 或 '+'. 如果在电子邮件地址的本地名称部分中的某些字符之间添加句点('.'),则发往那里的邮件将会转发到本地名称中没有点的同一地址.例如,"[email protected]" 和 "[email protected]" 会转发到同一电子邮件

423. Reconstruct Original Digits from English (leetcode)

Given a non-empty string containing an out-of-order English representation of digits 0-9, output the digits in ascending order. Note: Input contains only lowercase English letters. Input is guaranteed to be valid and can be transformed to its origina