题目:EPI
搜狗实习生面试中出现过一道题,“给出一个字符串,找出一个最短子串,该子串包括字符串出现过的所有字符”。
代码如下(还能进一步优化):
string find_substring_contain_all(const string &str)
{
if (str.empty())
return "";
unordered_map<char, int> hmap;
//第一次扫描str,记录有几种字符
for (int i = 0; i < str.size(); i++)
hmap[str[i]]++;
int size = hmap.size();
hmap.clear();
int left = 0, right = 0;
//重新建立hmap,left==0时,正好包含所有种字符,
while (hmap.size() != size)
{
hmap[str[right]]++;
right++;
}
right--;//后退一位,这时[left,right]之间的字符串包含所有字符
int markleft = 0, markright = right, length = markright + 1;
hmap[str[left]]--;
if (hmap[str[left]] == 0)
{
hmap.erase(str[left]);
}
left++;
while (true)
{
//包含所有字符时,左指针右移
if (hmap.size() == size)
{
//出现更短的子字符串,更新记录
if (right - left + 1 < length)
{
markleft = left;
markright = right;
length = markright - markleft + 1;
}
hmap[str[left]]--;
//注意删除hmap记录为零的项
if (hmap[str[left]] == 0)
{
hmap.erase(str[left]);
}
left++;
}
else
{
right++;
if (right >= str.size())
{
right--;
break;
}
hmap[str[right]]++;
}
}
string res(str.begin() + markleft, str.begin() + markright+1);
return res;
}
进阶一:流操作(即只能往后读取数据,不能回头读取已经读过的数据)
//假设s是一种流,只能往后读取数据,不能回头读取已经读过的数据
pair<int, int> find_smallest_subarray(const vector<string> &s, const unordered_set<string> &Q)
{
pair<int, int> res(-1, -1);
if (Q.empty())
return res;
list<int> loc;//字符串最后出现的位置
unordered_map<string, list<int>::iterator> hmap;
int index = 0;
for (auto i = Q.begin(); i != Q.end(); i++)
hmap[*i] = loc.end();
while (index < s.size())
{
if (Q.find(s[index]) != Q.end())
{
auto i = hmap[s[index]];
if (i != loc.end())
{
loc.erase(i);
}
loc.push_back(index);
hmap[s[index]] = --loc.end();
if (loc.size() == Q.size() && ((res.first == -1 && res.second == -1) || (index - loc.front() < res.second - res.first)))
{
res = make_pair(loc.front(), index);
}
}
index++;
}
return res;
}
进阶二:最短的连续子序列需要按照原子集Q的先后顺序
pair<int, int> find_smallest_sequentially_subset(const vector<string> &A, const vector<string> &Q)
{
pair<int, int> res(-1, A.size());
if (A.empty() || Q.empty())
return res;
unordered_map<string, int> K;
vector<int> L(Q.size(), -1), D(Q.size(), INT_MAX);
//初始化K
for (int i = 0; i < Q.size(); i++)
K[Q[i]] = i;
for (int i = 0; i < A.size(); i++)
{
auto iter = K.find(A[i]);
if (iter != K.end())
{
int index = iter->second;
//更新L
L[index] = i;
//更新D
if (index == 0)
D[0] = 1;
else if (D[index - 1] != INT_MAX)
D[index] = i - L[index - 1] + D[index - 1];
//更新res
if (index == Q.size() - 1 && D[index] < res.second - res.first + 1)
{
//注意,res.first = L[0]是错的!因为此时以L[0]开始的部分可能还没有形成整个Q。
res.first = i - D[index] + 1;
res.second = i;
}
}
}
return res;
}