KMP喜提我狗命
字符串hash初步
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
int hashFunc(char S[], int len) { int id = 0; for(int i = 0; i < len; i++) { id = id * 26 + (S[i] - 'A'); } return id; }
int hashFunc(char S[], int len) { int id = 0; for(int i = 0; i < len; i++) { if(S[i] >= 'A' && S[i] <= 'Z') { id = id * 52 + (S[i] - 'A'); }else if(S[i] >= 'a' && S[i] <= 'z') { id = id * 52 + (S[i] - 'a') + 26; } } return id; }
int hashFunc(char S[], int len) { int id = 0; for(int i = 0; i < len - 1; i++) { id = id * 26 + (S[i] - 'A'); } id = id * 10 + (S[len - 1] - '0'); }
|
字符串hash进阶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
#include <iostream> #include <string> #include <vector> #include <algorithm> 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.size(); 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; }
|
KMP 算法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
|
void getNext(char s[], int len) { next[0] = -1; int j = next[0]; for(int i = 1; i < len; i++) { while(j != -1 && s[i] != s[j + 1]) j = next[j]; if(s[i] == s[j + 1]) j++; next[i] = j; } }
bool KMP(char text[], char pattern[]) { int n = strlen(text), m = strlen(pattern); getNext(pattern, m); int j = -1; for(int i = 0; i < n; i++) { while(j != -1 && text[i] != pattern[j + 1]) j = next[j]; if(text[i] == pattern[j + 1]) j++; if(j == m - 1) return true; } return false; }
int KMP(char text[], char pattern[]) { int n = strlen(text), m = strlen(pattern); getNext(pattern, m); int j = -1, ans = 0; for(int i = 0; i < n; i++) { while(j != -1 && text[i] != pattern[j + 1]) j = next[j]; if(text[i] == pattern[j + 1]) j++; if(j == m - 1) { ans++; j = next[j]; } } return ans; }
void getNextval(char s[], int len) { int j = -1; netxval[0] = -1; for(int i = 1; i < len; i++) { while(j != -1 && s[i] != s[j + 1]) j = nextval[j]; if(s[i] == s[j + 1]) j++; if(j == -1 || s[i + 1] != s[j + 1]) nextval[i] = j; else nextval[i] = nextval[j]; } }
|