这一题学到了新的技巧,以及需要注意的很多细节(类似这种竞赛题目和平时leetcode做题目的区别)
首先是小数据集的做法:
很自然的,对dict里面的每个词在字符串里面找是不是有符合条件的子串,找的时候肯定使用滑动窗口,计算每个字符出现的频率。
然后是大数据集的做法:
不能够使用一个词一个词地找这种做法,因为词的数量太多。但是考虑到:如果所有词的长度和为M,那么不同长度的数量最多为sqrt(M)(1,2,3。。。这样的)。所以可以每次看一个长度的。
但是怎么看一个长度的呢?难道是设置窗口大小为这么大,然后每滑动一次,就把所有的这个长度的词都遍历一遍吗?不是,还有更好的方法。
这里使用的是hash的方法,这一个hash就可以解决:1.首尾字母是否相同2.出现的字母频率是否都相同。这就是它神奇的地方,不然使用我那个方法的话,太浪费了。
先看代码:
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <unordered_map>
#include <unordered_set>
using namespace std;
int seed = 13331;
unsigned long long getHash(char a, char b, vector<int>& freq) {
unsigned long long res = seed*a + b;
for (int i = 0; i < 26; ++i)
res = res * seed + freq[i];
return res;
}
string getStr(char s1, char s2, int n, int a, int b, int c, int d);
int main