|
| 1 | +# 字符串匹配算法 |
| 2 | + |
| 3 | +在一个长字符串或文章中,找出它是否包含一个或多个模式字符串及其位置。可以应用于生物基因匹配、信息检索等。 |
| 4 | + |
| 5 | +## Brute Force |
| 6 | + |
| 7 | +数据量不大的情况下,可以使用固定长度的滑动窗口枚举长串的所有子串,逐一与模式串进行比较。 |
| 8 | + |
| 9 | +- 防御性编程(如模式串长度大于长串长度) |
| 10 | +- 初始化长度为模式串长度的滑动窗口 |
| 11 | +- 将当前窗口的子串与模式串进行比较,若匹配成功,则记录相关信息如下标等 |
| 12 | +- 将滑动窗口后移一格 |
| 13 | + |
| 14 | +## Rabin-Karp (RK) |
| 15 | + |
| 16 | +Rabin-Karp 是用于字符串匹配的算法 |
| 17 | + |
| 18 | +JavaScript Code |
| 19 | + |
| 20 | +TODO |
| 21 | + |
| 22 | +```js |
| 23 | +/** |
| 24 | + * @param {string} haystack |
| 25 | + * @param {string} needle |
| 26 | + * @return {number} |
| 27 | + */ |
| 28 | +var strStr = function (haystack, needle) { |
| 29 | + if (!haystack || !needle || haystack.length < needle.length) return -1; |
| 30 | + |
| 31 | + const n = haystack.length, |
| 32 | + m = needle.length; |
| 33 | + |
| 34 | + let hash1 = initHash(haystack, 0, m); |
| 35 | + const hash2 = initHash(needle, 0, m); |
| 36 | + |
| 37 | + for (let i = 0; i <= n - m; i++) { |
| 38 | + if (i > 0 && i <= n - m) { |
| 39 | + hash1 = rehash(haystack, hash1, i - 1, i + m - 1, m); |
| 40 | + } |
| 41 | + |
| 42 | + if (hash1 === hash2 && compare(haystack, needle, i)) { |
| 43 | + return i; |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + return -1; |
| 48 | + |
| 49 | + // ******************************************** |
| 50 | + function initHash(string, start, end) { |
| 51 | + let hashVal = 0; |
| 52 | + for (let i = start; i < end; i++) { |
| 53 | + const c = string[i]; |
| 54 | + hashVal += |
| 55 | + (c.charCodeAt(0) - 'a'.charCodeAt(0)) * |
| 56 | + Math.pow(26, end - start); |
| 57 | + } |
| 58 | + return hashVal; |
| 59 | + } |
| 60 | + |
| 61 | + function rehash(string, hashVal, oldIdx, newIdx, patLen) { |
| 62 | + return ( |
| 63 | + (hashVal - |
| 64 | + (string.charCodeAt(oldIdx) - 'a'.charCodeAt(0) + 1) * |
| 65 | + Math.pow(26, patLen - 1)) * |
| 66 | + 26 + |
| 67 | + (string.charCodeAt(newIdx) - 'a'.charCodeAt(0) + 1) |
| 68 | + ); |
| 69 | + } |
| 70 | + |
| 71 | + function compare(string, pattern, start) { |
| 72 | + for (let i = 0; i < pattern.length; i++) { |
| 73 | + if (string[i + start] !== pattern[i]) return false; |
| 74 | + } |
| 75 | + return true; |
| 76 | + } |
| 77 | +}; |
| 78 | + |
| 79 | +var a = strStr('lcode', 'code'); |
| 80 | + |
| 81 | +console.log(a); |
| 82 | +``` |
0 commit comments