嗯先贴一个最初的实现,思路是对的,但是编码能力太差,写出来有问题。
class Solution {
public:
vector<int> findSubstring(string S, vector<string> &L) {
int llen = L[0].length();
vector<int> res;
if (S == "")
return res;
vector<bool> used;
for (int i = 0; i < L.size(); ++i)
used.push_back(false);
for (int i = 0; i < S.length(); ++i) {
for (int j = 0; j < L.size(); ++j)
used[j] = false;
int j;
for (j = 0; j < L.size() && i + (j + 1) * llen <= S.length(); ++j) {
if (!isValid(S.substr(i + j * llen, llen), L, used)) {
i = i + j * llen;
break;
}
}
if (j == L.size())
res.push_back(i);
}
}
bool isValid(string s, vector<string> &L, vector<bool> &used) {
int index = -1;
for (int i = 0; i < L.size(); ++i) {
if (s == L[i] && used[i] == false)
index = i;
}
if (index == -1)
return false;
used[index] = true;
return true;
}
};
目前的结论是,我之前的思路是正确的,使用map可以大大加快速度。并且,由于STL效率差,因此能不重复做的工作坚决不重复做。
class Solution {
public:
vector<int> findSubstring(string S, vector<string> &L) {
vector<int> res;
if (S == "")
return res;
map<string, int> words;
map<string, int> curStr;
for (int i = 0; i < L.size(); ++i)
++words[L[i]];
int len = L.size() * L[0].length();
for (int i = 0; i + len <= S.length(); ++i) {
if (isValid(S.substr(i, len), L, words, curStr))
res.push_back(i);
}
return res;
}
bool isValid(string s, vector<string> &L, map<string, int> &words, map<string, int> &curStr) {
curStr.clear();
int wordLen = L[0].length();
for (int i = 0; i + wordLen <= s.length(); i += wordLen) {
string sub = s.substr(i, wordLen);
if (words.find(sub) == words.end())
return false;
++curStr[sub];
if (curStr[sub] > words[sub])
return false;
}
return true;
}
};
http://oj.leetcode.com/problems/substring-with-concatenation-of-all-words/