|
| 1 | +import 'SubstringMatchHelper.dart'; |
| 2 | +import 'FileOperator.dart'; |
| 3 | + |
| 4 | +/** |
| 5 | + * 字符串匹配 |
| 6 | + */ |
| 7 | +class SubstringMatch { |
| 8 | + //粗暴强制 |
| 9 | + static int bruteforce(String s, String t) { |
| 10 | + if (s.length < t.length) return -1; |
| 11 | + // s[i, i + t.length - 1] |
| 12 | + for (int i = 0; i + t.length - 1 < s.length; i++) { |
| 13 | + int j = 0; |
| 14 | + for (; j < t.length; j++) |
| 15 | + if (s[i + j] != t[j]) break; |
| 16 | + if (j == t.length) return i; |
| 17 | + } |
| 18 | + return -1; |
| 19 | + } |
| 20 | + |
| 21 | + static int rabinKarp(String s, String t) { |
| 22 | + if (s.length < t.length) return -1; |
| 23 | + if (t.length == 0) return 0; |
| 24 | + |
| 25 | + int thash = 0, |
| 26 | + B = 256; |
| 27 | + double MOD = 1e9 + 7; |
| 28 | + for(int i = 0; i < t.length; i ++){ |
| 29 | + thash = ((thash * B + t[i].codeUnits[0]) % MOD).toInt(); |
| 30 | + }; |
| 31 | + int hash = 0, P = 1; |
| 32 | + for(int i = 0; i < t.length - 1; i ++) |
| 33 | + P = (P * B % MOD).toInt(); |
| 34 | + |
| 35 | + for(int i = 0; i < t.length - 1; i ++) |
| 36 | + hash = ((hash * B + s[i].codeUnits[0]) % MOD).toInt(); |
| 37 | + |
| 38 | + for(int i = t.length- 1; i < s.length; i ++){ |
| 39 | + hash = ((hash * B + s[i].codeUnits[0]) % MOD).toInt(); |
| 40 | + if(hash == thash && _equal(s, i - t.length + 1, t)) |
| 41 | + return i - t.length + 1; |
| 42 | + hash = ((hash - s[i - t.length + 1].codeUnits[0] * P % MOD + MOD) % MOD).toInt(); |
| 43 | + } |
| 44 | + return |
| 45 | + - |
| 46 | + 1; |
| 47 | + } |
| 48 | + |
| 49 | + static bool _equal(String s, int l, String t) { |
| 50 | + for (int i = 0; i < t.length; i ++) |
| 51 | + if (s[l].codeUnits[0] + i != t[i].codeUnits[0]) return false; |
| 52 | + return true; |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +void main() async { |
| 57 | + String s1 = "hello, this is liuyubobobo."; |
| 58 | + String t1 = "bo"; |
| 59 | + SubstringMatchHelper.matchTest("bruteforce", s1, t1); |
| 60 | + |
| 61 | + List s2 = await FileOperator.getFileString("text2.txt"); |
| 62 | + String t2 = "china"; |
| 63 | + StringBuffer res = new StringBuffer(); |
| 64 | + for (int i = 0; i < s2.length; i++) { |
| 65 | + res.write(s2[i]); |
| 66 | + } |
| 67 | + |
| 68 | + SubstringMatchHelper.matchTest("bruteforce", res.toString(), t2); |
| 69 | + |
| 70 | + SubstringMatchHelper.matchTest("bruteforce", res.toString(), "zyx"); |
| 71 | + |
| 72 | + /// Worst case |
| 73 | + int n = 1000000, |
| 74 | + m = 1000; |
| 75 | + |
| 76 | + StringBuffer s3 = new StringBuffer(); |
| 77 | + for (int i = 0; i < n; i++) |
| 78 | + s3.write('a'); |
| 79 | + |
| 80 | + StringBuffer t3 = new StringBuffer(); |
| 81 | + for (int i = 0; i < m - 1; i++) |
| 82 | + t3.write('a'); |
| 83 | + t3.write('b'); |
| 84 | + |
| 85 | + SubstringMatchHelper.matchTest("bruteforce", s3.toString(), t3.toString()); |
| 86 | +} |
0 commit comments