Isomorphic Strings
题意:给出一个字符串,在其中指定两个相同长度的字串,判断是否为同构字符串(相同位置的字母的映射关系是否唯一)
思路:字符串hash,判断每个字母的hash值是否相同
代码:
1 #include<cstdio> 2 #include<vector> 3 #include<algorithm> 4 using namespace std; 5 typedef long long ll; 6 const int maxn=2e5+10; 7 const ll MOD=1e9+7; 8 ll h[26][maxn],x=107,px[maxn]; 9 char s[maxn]; 10 int main() 11 { 12 int n,m; 13 scanf("%d%d", &n,&m); 14 scanf("%s", s+1); 15 px[0]=1; 16 for(int i = 1; i <= n; ++i) px[i]=px[i-1]*x%MOD; 17 for(int i = 0; i < 26; ++i) 18 { 19 for(int j = 1; j <= n; ++j) 20 h[i][j]=(h[i][j-1]*x+int(s[j] == (i+'a')))%MOD; 21 } 22 while(m--) 23 { 24 int x,y,l; 25 scanf("%d%d%d", &x,&y,&l); 26 vector<int> p,q; 27 for(int i = 0; i < 26; ++i) 28 { 29 p.push_back(((h[i][x+l-1]-px[l]*h[i][x-1]%MOD)%MOD+MOD)%MOD); 30 q.push_back(((h[i][y+l-1]-px[l]*h[i][y-1]%MOD)%MOD+MOD)%MOD); 31 } 32 sort(q.begin(),q.end());sort(p.begin(),p.end()); 33 printf("%s\n", p==q? "YES":"NO"); 34 } 35 return 0; 36 }
浙公网安备 33010602011771号