给出N个只有小写字母的字符串,求其中的不同的字符串的个数
#include<iostream> #include<string> #include<algorithm> #include<vector> using namespace std; const int MOD = 1000000007; const int P = 10000019; vector<int> ans; long long hashFunc(string str) { long long H = 0; for (int i = 0; i < str.length(); i++) { H = (H * P + str[i] - 'a') % MOD; } return H; } int main() { string str; while (getline(cin, str), str != "#") { long long id = hashFunc(str); ans.push_back(id); } sort(ans.begin(), ans.end()); int count = 0; for(int i = 0; i < ans.size(); i++){ if (i == 0 || ans[i] != ans[i - 1]) { count++; } } cout<<count<<endl; return 0; }
输入两个长度不超过1000的字符串,求他们的最长公共子串的长度。
计算出各个子串的Hash值,与长度保存成pair对。比较
#include<iostream> #include<cstdio> #include<string> #include<vector> #include<map> #include<algorithm> using namespace std; typedef long long LL; const LL MOD = 100000007; const LL P = 10000019; const LL MAXN = 1010; LL powP[MAXN], H1[MAXN] = { 0 }, H2[MAXN] = { 0 }; vector<pair<int, int> > pr1, pr2; void init(int len) { powP[0] = 1; for (int i = 1; i <= len; i++) { powP[i] = (powP[i - 1] * P) % MOD; //每一步取模,防止溢出 } } void calH(LL H[], string& str) { H[0] = str[0]; for (int i = 1; i < str.length(); i++) { H[i] = (H[i - 1] * P + str[i]) % MOD; //直接用str[i] } } int calSingleSubH(LL H[], int i, int j) { if (i == 0) return H[j]; return((H[j] - H[i - 1] * powP[j - i + 1]) % MOD + MOD) % MOD; } void calSubH(LL H[], int len, vector<pair<int, int>>& pr) { for (int i = 0; i < len; i++) { for (int j = i; j < len; j++) { int hashValue = calSingleSubH(H, i, j); pr.push_back(make_pair(hashValue, j - i + 1)); } } } int getMax() { int ans = 0; for (int i = 0; i < pr1.size(); i++) { for (int j = 0; j < pr2.size(); j++) { if (pr1[i].first == pr2[j].first) {//hash值相等 ans = max(ans, pr1[i].second); } } } return ans; } int main() { /* ILoveYou YouDontLoveMe */ string str1, str2; getline(cin, str1); getline(cin, str2); init(max(str1.length(), str2.length())); calH(H1, str1); calH(H2, str2); calSubH(H1, str1.length(), pr1); calSubH(H2, str2.length(), pr2); printf("ans = %d\n", getMax()); return 0; }