算法设计与分析第十一周——动态规划之Concatenated Words

KITTI数据集下载及解析 KITTI数据集下载及解析 版本 更新时间 更新内容 作者 1 V 1.0 xxx 完成主体内容 W. Xiao 2 文章目录KITTI Dataset1 简介1.1 数据采集平台1.2 坐标系2 数据解析2.1 image文件2.2 velodyne文件2.3 calib文件2.4 label文件3 KITTI可视... 阅读详情

算法设计与分析第十一周——动态规划之Concatenated Words

      这周还是继续做动态规划相关的题目—— 472. Concatenated Words


题目详情

      题目为给出一个字符串集合,找出里面所有的可以由其他字符串(最少两个)组成的字符串。字符串集合里的字符串全是两两不相同的。

      输入样例及其解释如下:

输入输出解释
["cat","cats","catsdogcats",
"dog","dogcatsdog",
"hippopotamuses","rat",
"ratcatdogcat"]
["catsdogcats",
"dogcatsdog",
"ratcatdogcat"]
字符串"catsdogcats"能够由字符串集合里的"cats"和"dog"组成,其他字符串类似。

题目分析与算法设计

      咋一看,跟之前博主写的Word break(详情可转至Word Break)十分相像,只要把字符串集合里的每一个字符串作为Word break里的s字符串输入,剩余的集合里的所有字符串组成了Word break的字符串词典,就能判断该传入的字符串s能否分裂成字典里的字符串了,即在s可以由字典的字符串组成。

      于是,便开始愉快的编写我的程序了,维护一个保存结果的字符串数组 ans,初始化为空集合。可以把之前的wordBreak(string s, vector<string>& wordDict) 函数(返回类型为bool)作为接口,对该题目给定的字符串数组的每一项都进行判断,如果该项可以被拆分,那么加入到 ans 中,遍历给定字符串数组,最后返回 ans。


代码详情

class Solution {
private: 
    set<string> mywords;
public:
    bool isConcatenatedWord(int& index, vector<string>& words) {
        string currstr = words[index];
        
        for (int i = 0; i < words.size(); i ++) {
            if (i != index) {
                mywords.insert(words[i]);
            } 
        }
        
        bool dp[currstr.size() + 1];
        memset(dp, false, currstr.size() + 1);
        dp[0] = true;
        
        for (int j = 1; j <= currstr.size(); j ++) {
            for (int i = j - 1; i >= 0; i --) {
                if (dp[i] && mywords.find(currstr.substr(i, j - i)) != mywords.end()) {
                    dp[j] = true;
                }
            }
        }
        mywords.clear();
        return dp[currstr.size()];
    }
    
    vector<string> findAllConcatenatedWordsInADict(vector<string>& words) {
        if (words.empty()) return vector<string>();
        vector<string> ans;
        
        for (int i = 0; i < words.size(); i ++) {
            if (words[i] != "" && isConcatenatedWord(i, words)) {
                ans.push_back(words[i]);
            }
        }
        return ans;
    }
};

     测试了一下,发现题目给出的样例是完全满足的,但是提交之后发现出现TLE(Time Limit Exceeded),也就是超时了,确实,上面的算法的复杂度是比较高的,最差为 O(m * n ^ 2),其中 m 为字符串集合的长度,n 为最长字符串的长度。

      稍作优化修改之后得到以下的代码:

class Solution {
private:
    set<string> mywords;
public:
    bool isConcatenatedWord(int& index, vector<string>& words) {
        string currstr = words[index];
        
        int n = currstr.size();
        vector<bool> dp(n + 1, false);
        dp[0] = true;
        
        for (int i = 0; i < n; i ++) {
            if (!dp[i]) continue;
            for (int j = i + 1; j <= n; j ++) {
                if (j - i < n && mywords.find(currstr.substr(i, j - i)) != mywords.end()) {
                    dp[j] = true;
                }
            }
            if (dp[n]) return true;
        }
        
        return dp[n];
    }
    
    vector<string> findAllConcatenatedWordsInADict(vector<string>& words) {
        if (words.empty()) return vector<string>();
        mywords = set<string>(words.begin(), words.end());
        vector<string> ans;
        
        for (int i = 0; i < words.size(); i ++) {
            if (words[i] != "" && isConcatenatedWord(i, words)) {
                ans.push_back(words[i]);
            }
        }
        return ans;
    }
};

 主要的修改有两处:

  1. 第13行的 if (!dp[i]) continue; 此处省去了之前的当前的字符串在 i 处不能被拆分仍遍历查询的情况,减少了无用的遍历
  2. 第19行的 if (dp[n]) return true; 当查到当前字符串可以被拆分,就直接返回真,而不用继续去遍历剩下的情况。

总结与思考

     如何把一些无用的遍历考虑到,进而对自己的代码在不更改基本框架和结构的前提下尽可能的优化,也是十分重要的。

     谢谢阅读。

Altera USB-Blaster在Win10/Win11的驱动兼容性处理 解决Altera USB-Blaster在Windows 10和Windows 11系统下的驱动兼容性问题,详细演示如何手动安装更新altera usb-blaster驱动安装,确保下载电缆正常识别,提升开发调试效率。 阅读详情

相关推荐

[yolov5/yolov8修改]替换yolov5/yolov8中的主干网络为EfficientNetv2

针对yolov5和yolov8的主干网络进行替换。

PLH19990227的博客 4122

LeetCode 472. Concatenated Words

LeetCode 472. Concatenated Words

浮生琴弦 2844

下载igv报错:Error loading genome hg38raw.githubusercontent.com...如何解决?

🏆本文收录于 《全栈 Bug 调优(实战版)》 专栏。专栏聚焦真实项目中的各类疑难 Bug,从成因剖析 → 排查路径 → 解决方案 → 预防优化全链路拆解,形成一套可复用、可沉淀的实战知识体系。无论你是初入职场的开发者,还是负责复杂项目的资深工程师,都可以在这里构建一套属于自己的「问题诊断性能调优」方法论,助你稳步进阶、放大技术价值 。

**My Coding Family** 926

Concatenated Words

Given a list of words (without duplicates), please write a program that returns all concatenated words in the given list of words. A concatenated word is defined as a string that is comprised entirel...

leetcode 解题思路 334

472. Concatenated Words

Given a list of words (without duplicates), please write a program that returns all concatenated words in the given list of words. A concatenated word is defined as a string that is comprised entirel...

weixin_30487701的博客 108

[LeetCode]Concatenated Words

Given a list of words (without duplicates), please write a program that returns all concatenated words in the given list of words. A concatenated word is defined as a string that is comprised entir

小熊听 392

472 Concatenated Words

1 题目 Given a list of words (without duplicates), please write a program that returns all concatenated words in the given list of words. A concatenated word is defined as a string that is comprised e...

weixin_39145266的博客 138

Leetcode 472. Concatenated Words

问题描述: Given a list of words (without duplicates), please write a program that returns all concatenated words in the given list of words. A concatenated word is defined as a string that is compr

u010370157的博客 417

472-Concatenated Words

Description: Given a list of words (without duplicates), please write a program that returns all concatenated words in the given list of words. A concatenated word is defined as a string that is com...

fighting! 489

关于句子embedding的一些工作简介(三)---- Concatenated p-mean Word Embeddings

这篇论文产生sentence embedding的方法非常简单,但是效果并不差,算是极简主义的一次胜利。由于其简单易操作,尽管过去由一些论文自称为hard/tough-to-beat的baseline,作者把自己的工作称为一个much harder-to-beat baseline。从实际效果看,此言不虚。 最简单的求sentence embedding的方法是对句子里所有的单词embeddin...

triplemeng的博客 3253

leetcode-472. Concatenated Words

考察点:dp,看是否一个string可以由其他string组成的变种; 思路:首先要会一个string可以由其他string组成这道题。然后就可以依次按照string的length长短来判断是否满足上一道字问题。注意一点的是再判断时在第二个for循环下j应该按照从0到i的遍历一次而不是按照string集合去遍历,因为那样会超时。C++ 代码:class Solution { public:

u014257954的专栏 1149

LeetcodeConcatenated Words

题目: 代码: 方法一——: class Solution { public: vector<string> findAllConcatenatedWordsInADict(vector<string>& words) { if (words.size() <= 2) return {}; vector<string> res; unordered_set<string> dict(

qq_35455503的博客 241

[Leetcode] 472. Concatenated Words 解题报告

题目: Given a list of words (without duplicates), please write a program that returns all concatenated words in the given list of words. A concatenated word is defined as a string that is compri

魔豆(Magicbean)的博客 1682

[图像超分]--FC2N:Fully Channel-Concatenated Network for Single Image Super-Resolution

创新点: 目前SOTA单帧图像超分方法如RCAN、EDSR的basic block为上图c的结构, 即为resnet的残差模块去除掉BN层,本文提出的结构为上图的f结构,使用加权concat替换残差部分,即element-wise相加的结构。 本文网络主体如图,主要由n个CG模块组成,最后是一个CG模块加权concat。每个CG模块里面包含了m个上面介绍的basic block。 实验结果:...

weixin_42096202的博客 1576

超分辨率图像理解

参考: http://www.ilovematlab.cn/viewthread.php?tid=111929&extra=page%3D1%26amp%3Bfilter%3Dtype%26amp%3Btypeid%3D1待整理

lyqmath的专栏 3294

超分辨率——Meta-SR: A Magnification-Arbitrary Network for Super-Resolution

2019 CVPR University of Science and Technology of China 这篇文章,作者针对 以往的文章,都是针对于不同的scale factor,需要训练出一个不同的模型,因此作者提出Meta-SR,这种方法,是不同的scale factor只需要训练出一个模型。这篇优秀的文章,需要把论文小标题理一下: Abstract Introductio...

qq_29257201的博客 781

比例导引三自由度弹道仿真 MATLAB+GUI_比例导引弹道_弹道matlab_

本程序可以实现经典的比例导引弹道的仿真,效果明显

powerBuilder编绎成DLL格式需要的EN32T.H头文件

powerBuilder编绎成DLL格式需要的EN32T.H头文件PB编绎成DLL文件时,提示"Error opening file 'c:\windows\system32\cgen\en32t.h'" 这个错误的解决方法下载这个文件后,说明看我的博文:http://blog.csdn.net/aasmfox/archive/2010/12/25/6097561.aspx希望对需要的菜鸟有所帮助哈哈,想不到真的有人下载这个东西。还是用PB12的版本好啦。

上一篇: 算法设计与分析第十周——动态规划之Perfect Squares
下一篇: 算法设计与分析第十二周——动态规划之 K Inverse Pairs Array
Cariver
博客等级 码龄10年 1粉丝 21原创
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值