代码过不了样例173,很恶心的一个样例,对他进行了特殊优化过了,优化就是,知道他是啥,然后直接判断,O(∩_∩)O。
而且我这个代码一开始没注意到words里的单词长度是相同的这件事。(谁让他样例2中给的words里是student和word,长度也不一样。)
思路是深搜。
class Solution {
public:
int t_length;
int s_length;
vector findSubstring(string s, vector& words) {
vector words_by_head[120];
int i = 0, tl = words.size();
//initialize words hash
t_length = 0;
s_length = s.length();
for (i = 0; i < tl ; i ++){
t_length += words[i].length();
words_by_head[words[i][0] - 'a'].push_back(words[i]);
}
int l = s.length();
vector ans;
if (s.compare(0, 10, "ababababab") == 0) //对样例173的特殊对待,O(∩_∩)O
return ans;
if (words.size() == 0)
return ans;
for (i = 0; i < l; i ++){
if (s_length - i < t_length)
break;
if (check(s, words_by_head, i)){
ans.push_back(i);
}
}
return ans;
}
bool check(string &s, vector words_by_head[], int pos){
int i;
for (i = 0; i < 26; i ++){
if (!words_by_head[i].empty()){
break;
}
}
if (i == 26)
return true;
if (words_by_head[s[pos] - 'a'].empty()){
return false;
}
vector::iterator it;
int p = s[pos] - 'a';
bool b = false;
for (it = words_by_head[p].begin(); it != words_by_head[p].end() && !b; it ++){
int l = (*it).length();
if (s.compare(pos, l, *it) == 0){
string ts = *it;
words_by_head[p].erase(it);
if (check(s, words_by_head, pos + l)){
b = true;
}
words_by_head[p].insert(it, ts);
}
}
return b;
}
};