Substring with Concatenation of All Words

本文介绍了一种用于查找字符串中特定子串的算法实现,并通过一个具体示例进行说明。该算法能够找出所有由给定单词集按顺序拼接而成的子串起始位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题链接

You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in wordsexactly once and without any intervening characters.

For example, given:
s: "barfoothefoobarman"
words: ["foo", "bar"]

You should return the indices: [0,9].
(order does not matter).

 

代码如下(这道题目题意理解有问题,只能通过约75%的测试用例):

     一个未通过的测试用例如下(s中good可以多于‘词典’中的个数):

Input:"wordgoodgoodgoodbestword" ["word","good","best","good"]
Output:[]
Expected:[8]
 
算法思路:
  我对于该题的题意理解与题目(给出的一个测试用例未能通过)本身应当是有分歧的,我是认为应当长度(也就是单词个数)应当一致才算匹配成功并返回其首字母下标!!
  我们假定词典中有wordNum个单词。
   每次都从s中挑选wordLen*wordNum长度的连续字符串str进行判定。我们对其中进行统计,一旦发现满足下面任何一个条件:
  (1)在词典dic中没有找到给定单词;
  (2)str中的某个单词的统计个数超过了dic中该单词的个数。
  我们即认为该str是不满足条件的,str应当向前移动一个单词的长度。否则将str的首字母的indices添加到结果集合中,同时str向前移动一个单词的长度。
  重复前面(紫色部分)的操作。
 1 class Solution {
 2 public:
 3     vector<int> findSubstring(string s, vector<string>& words) 
 4     {
 5         vector<int> res;
 6         
 7         int wordLen=words[0].size(),wordNum=words.size();
 8         if(s.size()<wordLen*wordNum)
 9             return res;
10         map<string,int> dic,curWord;
11         for(int i=0;i<wordNum;i++)
12             dic[words[i]]++;
13         for(int i=0;i<s.size()-wordLen*wordNum;i++)
14         {
15             curWord.clear();
16             int j;
17             for(j=0;j<wordNum;j++)
18             {
19                 string word=s.substr(i+j*wordLen,wordLen);
20                 if(dic.find(word)==dic.end())
21                     break;
22                 curWord[word]++;
23                 if(curWord[word]>dic[word])
24                     break;
25             }
26             if(j==wordNum)
27                 res.push_back(i);
28         }
29         return res;
30     }
31 };

 

转载于:https://www.cnblogs.com/chess/p/5140937.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值