一、 问题描述
Leecode第三十题,题目为:
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 words exactly once and without any intervening characters.
Example 1:
Input:
s = “barfoothefoobarman”,
words = [“foo”,“bar”]
Output: [0,9]
Explanation: Substrings starting at index 0 and 9 are “barfoor” and “foobar” respectively.
The output order does not matter, returning [9,0] is fine too.
Example 2:
Input:
s = “wordgoodgoodgoodbestword”,
words = [“word”,“good”,“best”,“word”]
Output: []
问题理解为:
给定一个字符串,s,和一系列单词,它们长度相同。在s中找到所有子字符串的起始索引,该索引是单词中每个单词的一次连接,并且不包含任何中间字符。
例1:
输入:
s =“barfoothefoobarman”,
words= (“foo”、“bar”)
输出:(0,9)
示例2:
输入:
s =“wordgoodgoodgoodbestword”,
words=[“word”,“good”,“best”,“word”)
输出:[]
说明:
从索引0和索引9开始的子字符串分别是“barfoor”和“foobar”。
输出顺序无关紧要,返回[9,0]也可以。
二、算法思路
1、
2、
三、实现代码
class Solution {public:vector<int> findSubstring(string S, vector<string> &L) {int l_size = L.size();if (l_size <= 0) {return vector<int>();}vector<int> result;map<string, int> wordcount;int wordlengh = L[0].size();int i, j;for (i = 0; i < l_size; ++i) {++wordcount[L[i]];}map<string, int> counting;for (i = 0; i <= (int)S.length() - (l_size * wordlengh); ++i) {counting.clear();for (j = 0; j < l_size; ++j) {string word = S.substr(i + j * wordlengh, wordlengh);if (wordcount.find(word) != wordcount.end()) {++counting[word];if (counting[word] > wordcount[word]) {break;}}else {break;}}if (j == l_size) {result.push_back(i);}}return result;}
};