当前位置:网站首页>Leetcode力扣题解 - 30.串联所有单词的子串
Leetcode力扣题解 - 30.串联所有单词的子串
2022-07-20 06:52:00 【就要 宅在家】
地址:30. 串联所有单词的子串 - 力扣(LeetCode)
一.思路
本题关键点是:
1.所有关键词长度一致。
2.匹配的是所有关键词连接起来的
大体思路:
那么我们就可以从字符串头开始,每次只匹配关键词总长度个字符。如果匹配成功,在返回的数组中保存起始位置即可。直到走到(字符串长度-关键词总长)的位置停止,因为此时是能保证匹配字符数目与关键词总数一致的最后位置。
字符与关键词匹配:
这里可以使用哈希表的方式来判断字符串与关键词是否匹配。
假设 字符串 = "barfoothefoobarman", 关键词 = ["foo","bar"]。
在第一趟中,需要匹配的是barfoo,此时我们创建一个哈希表。
因为关键词的长度固定。这里都是3,所以把此时的字符串barfoo分成bar、foo两个部分装入哈希表中,每装入一个对应的值加一。
我们再将关键词依次与哈希表匹配,每匹配成功一个,对应的哈希表值减一。
当关键词遍历完成后,如果哈希表中所有值都为0说明此时的字符串与关键词都匹配上了,否则就是没有匹配上。
二.代码
class Solution {
public:
vector<int> findSubstring(string s, vector<string>& words) {
vector<int> ret;//返回的数组
int m = words.size(), n = words[0].size();//确定关键词个数、长度
for(int i = 0; i + m * n < s.size() + 1; i++)//判断条件是走到最后一个字符串长度能与关键词总长一致
{
unordered_map<string, int> umap;//哈希表
for(int j = 0; j < m; j++)//将字符串拆分装入哈希表
{
umap[s.substr(i + j * n, n)]++;
}
for(string& word : words)//进行关键词与哈希表匹配
{
umap[word]--;
if(umap[word] == 0) umap.erase(word);
}
if(umap.empty()) ret.emplace_back(i);//匹配成功
}
return ret;
}
};
· “一名优秀的程序员,在穿越单行道时也会确认双向的来车情况。”——道格拉斯·林德(Doug Linder)
如有错误,敬请斧正
边栏推荐
- mpf4_ Pricing European American barrier options_ CRR_ Leisen-Reimer_ Greeks_ Binary tree trigeminal tree grid_ Fine differences (explicit implicit) crank Nicolson_ Imp volatility
- Threejst objects move at a constant speed
- 阶跃数特征
- 国内的边缘计算组织和产品调研
- 【递归 & 分治】压缩变换(使用区间树和二分法,递归统计指定区间内数字种类)
- Go 调度器——schedule
- 尚医通项目总结
- HCIP-7.OSPF的LSA头部
- 初学者必看Markdown 使用指南
- QBluetoothSocket
猜你喜欢
How to understand software testing with the 28 principle? See the following
通过STM32 stlink utility工具对ST-LINK芯片信息进行读取和升级以及SWD烧录媒介
Two dimensional convolution Chinese microblog emotion classification project
如果在加密领域有段位,你是“青铜”还是“王者”?
threejst物体匀速移动
尚医通项目总结
二分图--
Detailed explanation of five data types of redis
redis锁超卖解决问题
C language file operation management (Part 1)
随机推荐
【学习笔记】AGC016
Summary of relevant operations on deploying Drupal website on the server
【LeetCode】206. Reverse linked list
EV代码签名证书可以自助续签吗?
The realization of Sanzi game
Getting started with native threejs
国内的边缘计算组织和产品调研
[learning notes] radical thinking question
【学习笔记】整除分块、线性筛、莫比乌斯反演
[translation] thinking about machine learning engineering after a year of doctoral study
Step number characteristic
2022年软件测试最新面试题及解析
C# 反射与工厂模式
Rgb+ depth image semantic segmentation paper reading notes (icra2021)
Threejst objects move at a constant speed
Three practical PivotTable operating skills in Excel, simple and efficient!
[jzof-03] repeated numbers in the array
数论基础-
Detailed explanation of five data types of redis
One dimensional convolution English film review emotion classification project