ACM中常用的字符串算法不多,主要有以下几种:
- Hash
- 字典树
- KMP
- AC自动机
- manacher
- 后缀数组
- EX_KMP
- SAM(后缀自动机)
- 回文串自动机
一. Hash
hash常用算法:
1 #define M 249997 2 /*APHash*/ 3 unsigned int APHash(String str) 4 { 5 unsigned int hash = 0xAAAAAAAA; 6 for(int i = 0; i < str.length(); i++) 7 { 8 if((i & 1) == 0) 9 hash ^=((hash << 7) ^ str.charAt(i) ^ (hash >> 3)); 10 else 11 hash ^= (~((hash << 11) ^ str.charAt(i) ^ (hash >> 5))); 12 } 13 return (hash%M); 14 } 15 //RSHash 16 unsigned int RSHash(String str) 17 { 18 unsigned int b = 378551; 19 unsigned int a = 63689; 20 unsigned int hash = 0; 21 for(int i = 0; i < str.length(); i++) 22 { 23 hash = hash * a + str.charAt(i);//这里可能需要改成srt.At(i) 24 a = a * b; 25 } 26 return (hash%M); 27 } 28 /*DJBHash*/ 29 unsigned int DJBHash(String str) 30 { 31 unsigned int hash = 5381; 32 for(int i = 0; i < str.length(); i++) 33 hash = ((hash << 5) + hash) + str.charAt(i); 34 return (hash%M); 35 } 36 /*JSHash*/ 37 unsigned int JSHash(String str) 38 { 39 unsigned int hash = 1315423911; 40 for(int i = 0; i < str.length(); i++) 41 hash ^= ((hash << 5) + str.charAt(i) + (hash >> 2)); 42 return (hash%M); 43 } 44 /*SDBMHash*/ 45 unsigned int SDBMHash(String str) 46 { 47 unsigned int hash = 0; 48 for(int i = 0; i < str.length(); i++) 49 hash = str.charAt(i) + (hash << 6) + (hash << 16) - hash; 50 return (hash%M); 51 } 52 /*PJWHash*/ 53 unsigned int PJWHash(String str) 54 { 55 unsigned int BitsInUnsignedInt = (unsigned int)(sizeof(unsigned int)*8); 56 (unsigned int) ThreeQuarters = (unsigned int)((BitsInUnsignedInt * 3) / 4); 57 (unsigned int) OneEighth = (unsigned int)(BitsInUnsignedInt / 8); 58 (unsigned int) HighBits = (unsigned int)(0xFFFFFFFF)<<(BitsInUnsignedInt-OneEighth); 59 (unsigned int) hash = 0; 60 (unsigned int) test = 0; 61 for(int i = 0; i < str.length(); i++) 62 { 63 hash = (hash << OneEighth) + str.charAt(i); 64 if((test = hash & HighBits) != 0) 65 hash = ((hash ^ (test >> ThreeQuarters)) & (~HighBits)); 66 } 67 return (hash%M); 68 } 69 }
1 unsigned int BKDRHash(char*str) 2 { 3 unsigned int seed=131; 4 unsigned int hash=0 ; 5 for(int i = 0; i < str.length(); i++) 6 hash = (hash * seed) + str.charAt(i); 7 return(hash % M); 8 }
对于hash的理解可以见我另一份博客随笔,在算法专题栏中。