您的位置:首页 > 其它

[leetcode] 30. Substring with Concatenation of All Words 解题报告

2015-12-18 04:40 656 查看
题目链接:https://leetcode.com/problems/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).

思路:一种比较粗暴的方式就是先对words计数,然后在s的每个位置开始枚举固定的长度,如果能找到每个单词那就把当前的索引加到结果集合中.其实这样效率还是可以接受的.时间复杂度是O(n*k),其中n是s的长度,k是总共words的长度.

代码如下:

class Solution {
public:
vector<int> findSubstring(string s, vector<string>& words) {
if(s.size()==0 || words.size()==0) return {};
vector<int> result;
unordered_map<string, int> hash;
for(auto val: words) hash[val]++;
int m = words.size(), n = words[0].size(), len = s.size();
if(len < m*n) return {};
for(int i = 0, j; i <= len - m*n; i++)
{
unordered_map<string, int> find;
for(j = i; j < i + m*n; j+= n)
{
string tem = s.substr(j, n);
find[tem]++;
if(!hash.count(tem) || find[tem] > hash[tem]) break;
}
if(j >= i+m*n) result.push_back(i);
}
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: