题目链接:力扣
题目其实不难,用字符串哈希就可以解决,值得学习的是hash的计算方法。
先复习一下经典的字符串hash:acwing-841. 字符串哈希
思路就是把一个字符串"ABCDLJ```"看成是一个P进制的数(P一般取131),然后把每个子串的这个P进制转成十进制,计算出的就是hash值。注意这里的子串是以源字符串开头为开头的子串substr[0,n](比如"A","AB","ABC","ABCD","ABCDL","ABCDLJ",```)。通过这种方式可以计算出所有子串substr[l,r]的hash值。公式如下:
hashvalue[l,r]=hashvalue[r]-hashvalue[l-1]*p[r-l+1]
这里的p[r-l+1]是指p的r-l+1次方,因此可以提前预处理出p的所有次方值和substr[0,n]的hash值。
#include<iostream>
using namespace std;
typedef unsigned long long ULL; //hash值和p的所有次方太大了,会超int和LL的范围,所以用ULL
const int P=131; //把字符串转成P进制数
const int N=1e5+10; //字符串最大长度,也是p的最大次方
ULL p[N],h[N]; //p的所有次方&所有以字符串的开头为开头的子串的hash
int n,m;
string str;
//预处理出p的所有次方和每个以字符串的开头为开头的子串的hash(即h[1,n])
//题目给的字符串编号是从1开始,所以h的下标也是从1开始,h[0]没有意义
void init(){
p[0]=1;
for(int i=1;i<=n;i++){
p[i]=p[i-1]*P;
h[i]=h[i-1]*P+(str[i-1]-'a'+1);
}
}
//返回h[l,r]
ULL substring_hash(int l,int r){
ULL hashvalue=h[r]-h[l-1]*p[r-l+1];
return hashvalue;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
cin>>n>>m>>str;
init();
while(m--){
int l1,r1,l2,r2;
cin>>l1>>r1>>l2>>r2;
if(substring_hash(l1,r1)==substring_hash(l2,r2)) cout<<"Yes"<<endl;
else cout<<"No"<<endl;
}
return 0;
}
而本题的字符串hash计算方法与上面的略有不同。上面的计算方法可以精确计算出每个字母在字符串中的位置,会认为"ABD"和"DBA"不是一类,而本题要求把字母相同。顺序不同的字符串都归为一类,因此需要考虑新的hash计算方式,把字符的顺序省略掉。而本题的所有字母都是小写字母,因此可以考虑用26个质数来代替字母,做一个累乘运算(用合数的话会导致2(B)*10(J)=4(D)*5(5)这样的冲突)。计算出hash后把相同hash的字符串归为一类存下来就行。
class Solution {
public:
unordered_map<unsigned long long,vector<string>> h; //存字符串和hash的映射关系
int p=1e9+7;
int primes[26]={2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,103}; //质数表,用于hash
void hash(string s){
unsigned long long hashvalue=1;
for(int i=0;i<s.size();i++){
// hashvalue=(long long)hashvalue*(s[i]-'a'+2)%p;
hashvalue=hashvalue*primes[s[i]-'a']%p;
}
cout<<hashvalue<<endl;
h[hashvalue].push_back(s);
}
vector<vector<string>> groupAnagrams(vector<string>& strs) {
for(int i=0;i<strs.size();i++){
hash(strs[i]);
}
vector<vector<string>> res;
for(auto it=h.begin();it!=h.end();it++){
res.push_back(it->second);
}
return res;
}
};
注意本题的踩坑点:最大的hash值为101^100≈10^200,会溢出,所以需要mod一个质数。常见的质数:1e9+7/100003等等,这题用100003会冲突。