leetcode 30. Substring with Concatenation of All Words

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).

题目分析:给定字符串s,和字符串数组words,字符串数组中的字符串长度相等,返回由words中的字符串联,且每个字符串只出现一次的字符串s1在s中首次出现的下标。

解答分析:

1. 将words送入map<string, int> word;

2. 循环遍历,取s的部分子串s2;

3. 检验s2是否能由words组成。

实现代码:

class Solution {
public:
    vector<int> findSubstring(string s, vector<string>& words) {


vector<int> output;
int slen=s.size();
int wslen=words.size();
//考虑空数组的情况
if(!slen||!wslen)
return output;
int wlen=words[0].length();
map<string, int> word;
map<string, int> current;
//将worlds数组推入map容器中
for(vector<string>::iterator k=words.begin() ; k!=words.end(); ++k)
word[*k]++;
for(int i=0; i+wslen*wlen<=slen; i++)
{
current.clear();
int j=0;
for(j=0; j<wslen; j++)
{
string temp=s.substr(i+j*wlen, wlen);
if(word.find(temp)==word.end())
break;
++current[temp];
if(current[temp]>word[temp])
break;
}
if(j==wslen)
output.push_back(i);
}
return output;

}
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值