刚开始做此题时考虑的不完善,没有对L中出现重复的元素进行考虑,
有误的代码
class Solution {
public:
vector<int> findSubstring(string S, vector<string> &L)
{
vector<int> res;
int len = S.length();
int numOfWords = L.size();
if(len==0||numOfWords==0)
return res;
vector<string> flag;
int lenOfWord = L[0].length();
if(lenOfWord*numOfWords > len)
return res;
int tempSize = 0;
int indice = INT_MAX;
for(int i = 0; i < numOfWords; ++i)
{
if(!isFindSubstr(L[i], flag))
{
flag.push_back(L[i]);
}
}
numOfWords = flag.size();
int i;
for(i = 0; i < len; ++i)
{
if(isFindSubstr(S.substr(i,lenOfWord), L)&&tempSize==0)
{
//判断所有连续的
while(i < len)
{
string substr = S.substr(i,lenOfWord);
if(isFindSubstr(substr, L)&&!isFindSubstr(substr, flag))
{
indice = min(indice, i);
flag.push_back(substr);
tempSize ++;
i += lenOfWord;
}
else
{
--i;
break;
}
}
if(tempSize==numOfWords)
{
res.push_back(indice);
}
flag.clear();
indice = INT_MAX;
tempSize = 0;
}
}
return res;
}
bool isFindSubstr(string str, vector<string> &L)
{
for(int i = 0; i < L.size(); ++i)
{
if(str==L[i])
return true;
}
return false;
}
};
利用map后Accepted的代码
class Solution {
public:
vector<int> findSubstring(string S, vector<string> &L)
{
vector<int> res;
int len = S.length();
int numOfWords = L.size();
if(len==0||numOfWords==0)
return res;
int lenOfWord = L[0].length();
if(lenOfWord*numOfWords > len)
return res;
map<string, int> flag;
for(int i = 0; i < numOfWords; ++i)
{
flag[L[i]]++;
}
int indice = 0;
map<string, int> temp;
while(indice <= (len - lenOfWord*numOfWords))
{
bool flagTmp = true;
temp.clear();
for(int i = indice; i <= indice + lenOfWord*(numOfWords-1); i += lenOfWord)
{
string tmp = S.substr(i,lenOfWord);
if(flag.find(tmp) == flag.end())
{
flagTmp = false;
break;
}
temp[tmp]++;
if(temp[tmp]>flag[tmp])
{
flagTmp = false;
break;
}
}
if(flagTmp==true)
res.push_back(indice);
indice++;
}
return res;
}
};