字符串匹配算法对于一个开发来说肯定不会陌生,比如jdk中String类indexOf(),我们可以看看它的实现
static int indexOf(char[] source, int sourceOffset, int sourceCount,char[] target, int targetOffset, int targetCount,int fromIndex) {//目标字符串是空字符串且当前索引位置大于等于源字符串长度if (fromIndex >= sourceCount) {return (targetCount == 0 ? sourceCount : -1);}//边界数据if (fromIndex < 0) {fromIndex = 0;}if (targetCount == 0) {return fromIndex;}//最大匹配长度char first = target[targetOffset];int max = sourceOffset + (sourceCount - targetCount);for (int i = sourceOffset + fromIndex; i <= max; i++) {//在源字符串中查找第一个字符相同的索引if (source[i] != first) {while (++i <= max && source[i] != first);}//匹配剩余字符串if (i <= max) {int j = i + 1;int end = j + targetCount - 1;for (int k = targetOffset + 1; j < end && source[j]== target[k]; j++, k++);if (j == end) {/* Found whole string. */return i - sourceOffset;}}}return -1;}
实际上,String的indexOf方法就是采用比较简单的BF(Brute Force)算法,用暴力匹配的方式实现目标字符串查找的功能
在极端情况情况下,BF算法的时间复杂度可以达到O(n*m)
比如源字符串是”aaaaaaa……b”,目标字符串是”aaaa…..b”(目标字符串中的a数字小于源字符串中的a的个数)
可以看到,暴力匹配的算法虽然简单,但是性能是比较低的,实际在业务开发中我们的源字符串跟目标字符串不会太长,所以在使用过程中使用也是没有问题的。
curl ‘https://fat-local-life-open.hellobike.com/localLife/bd/private/biz/queryAllBusinessOpportunityList‘ \
-H ‘authority: fat-local-life-open.hellobike.com’ \
-H ‘sec-ch-ua: “ Not A;Brand”;v=”99”, “Chromium”;v=”90”, “Google Chrome”;v=”90”‘ \
-H ‘accept: application/json, text/plain, /‘ \
-H ‘sec-ch-ua-mobile: ?0’ \
-H ‘user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36’ \
-H ‘content-type: application/json;charset=UTF-8’ \
-H ‘origin: http://localhost:5081‘ \
-H ‘sec-fetch-site: cross-site’ \
-H ‘sec-fetch-mode: cors’ \
-H ‘sec-fetch-dest: empty’ \
-H ‘accept-language: zh-CN,zh;q=0.9’ \
—data-raw ‘{“pageSize”:20,”pageIndex”:1,”bizToken”:”8c38d5735fb0417a9b4af703854a6d13”,”__sysTag”:”vpos-f0”}’ \
—compressed
