- 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 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: []
题目详解:
1.此题得难度在于words中单词可重复;
2.单纯遍历给定字符串,无法判断;
3.思路是将words中每个单词存入map中,因可重复,故存入unordered_map;
4.因words中单词定长,可算出长度,故遍历给定字符串,只需到(字符串长度减去words中单词总长度);
代码:
#include "pch.h"
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
vector<int> findSubstring(string s, vector<string>& words) {
if (s.empty() || words.empty()) return {};
vector<int> resVec;//返回数组
int n = words.size(), len = words[0].size();
unordered_map<string, int> wordsMap;
for (auto &word : words) ++wordsMap[word];
for (int i = 0; i <= (int)s.size() - n * len; i++) {
unordered_map<string, int> sMap;
int j = 0;
for (j = 0; j < n; j++) {
string t = s.substr(i + j * len, len);//截取定长子字符串(words中单词定长)
if (!wordsMap.count(t)) break;//当前截取子字符串不在map中,终止
++sMap[t];
if (sMap[t] > wordsMap[t]) break;//子字符串值不相等,终止
}
if (j == n) resVec.push_back(i);//连续给定子字符串都相等,则为所要值
}
return resVec;
}
int main()
{
/*string s = "wordgoodgoodgoodbestword";
vector<string> words = { "word", "good", "best", "word" };*/
string s = "barfoothefoobarman";
vector<string> words = {"foo", "bar"};
vector<int> res = findSubstring(s, words);
for (int i = 0; i < res.size(); i++)
{
cout << res[i];
cout << "\n";
}
std::cout << "Hello World!\n";
system("PAUSE");
}
图文详解:
性能:
总结:此题目主要考察对Map得使用,采用其他方法可能比较费劲;容器得原理和理解,在数据结构中尤为重要;继续加油!