标签:
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).
本题是寻找字符串中子串集出现的位置,先对子串集做成字典,然后依次匹配。时间:568ms,代码如下:
class Solution { public: vector<int> findSubstring(string s, vector<string>& words) { vector<int> res; if (s.empty() || words.empty() || s.size() < words.size()*words[0].size()) return res; int searchEnd = s.size() - words.size() * words[0].size(); size_t wordLen = words[0].size(), wordNum = words.size(); map<string, int> total, submap; for (size_t i = 0; i < wordNum; ++i) total[words[i]]++; for (size_t i = 0; i <= searchEnd; ++i){ submap.clear(); size_t k = 0; for (size_t j = i; k < wordNum; j += wordLen, ++k){ string str = s.substr(j, wordLen); if (total.find(str) == total.end()) break; else if (++submap[str]>total[str]) break; } if (k == words.size()) res.push_back(i); } return res; } };
[LeetCode] #30 Substring with Concatenation of All Words
标签:
原文地址:http://www.cnblogs.com/Scorpio989/p/4575712.html