leetcode c++ 串联所有单词的子串
我的解:
时间击败了7.71%,内存击败了18.3%(挺垃圾的)
#include <vector>
using namespace std;
class Solution {
public:
vector<int> findSubstring(string s, vector<string>& words) {
int len_w = words.back().length();
int len_all = len_w * words.size();
int len_s = s.length();
vector<string> word;
word.assign(words.begin(), words.end());
std::sort(word.begin(), word.end());
std::unique(word.begin(), word.end());
vector<int> counts;
for (int i =0;i<word.size();i++)
{
counts.push_back(std::count(words.begin(), words.end(), word.at(i)));
}
bool flag;
vector<int> indexes;
vector<string> temp;
string str;
for (int i=0; i<len_s && (len_s-i)>=len_all;i++)
{
flag = true;
temp.clear();
for(int j =0;j < words.size();j++)
{
temp.push_back(s.substr(i+j*len_w,len_w));
}
for (int k =0;k<word.size();k++)
{
if(std::count(temp.begin(),temp.end(), word.at(k)) !=counts.at(k))
{
flag=false;
break;
}
}
if (flag)
{
indexes.push_back(i);
}
}
return indexes;
};
};