Leetcode030 substring-with-concatenation-of-all-words 字符串查找
题目描述
给出一个字符串S和一组单词L,L中单词的长度都相等,找出S中的符合以下要求的子串在S中的起始位置索引:子串为L中所有单词串联在一起(单词的顺序随意),L中的每个单词只出现一次,中间不能有其他的字符。
例如:给定S="barfoothefoobarman",L为["foo", "bar"],
返回的索引应该是[0,9].(不用关心给出索引的顺序)
You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters.
For example, given:
S:"barfoothefoobarman"
L:["foo", "bar"]
You should return the indices:[0,9].
(order does not matter).
思路:L中字符串长度相同,找出S中L所有单词组合,且数目一致的位置。
所以遍历时,i+length*L.size()<=S.size(),然后切割每个length的单词去查找,m1中存放L每个单词的出现次数,m2[tmp]<m1[tmp]时,才说明是对的,可以继续查找。当找到的tmp数==L.size()时,表明该位置是正确的。
class Solution { public: vector<int> findSubstring(string S, vector<string> &L) { vector<int> res; if(S.empty()||L.empty()) return res; map<string,int> m1,m2; for(int i=0;i<L.size();++i) { m1[L[i]] = m1[L[i]]==0?1:m1[L[i]]+1; } int length = L[0].size(); for(int i =0;i+length*L.size()<=S.size();++i) { m2.clear(); int j; for(j=0;j<L.size();++j) { string tmp = S.substr(i+j*length,length); if(m1[tmp]!=0&&m1[tmp]>m2[tmp]) { m2[tmp]=m2[tmp]==0?1:m2[tmp]+1; } else break; } if(j==L.size()) { res.push_back(i); } } return res; } };
联系方式:emhhbmdfbGlhbmcxOTkxQDEyNi5jb20=
分类:
leetcode
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了