国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 學(xué)院 > 開(kāi)發(fā)設(shè)計(jì) > 正文

28. Implement strStr() 以及KMP算法的實(shí)現(xiàn)

2019-11-11 04:09:42
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

28. Implement strStr()

題目描述

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

代碼實(shí)現(xiàn)

這里需要注意的是不需要把母字符串全部迭代一次,只需要到還剩下子串長(zhǎng)度的索引地方。 代碼一:

class Solution {public: int strStr(string haystack, string needle) { int h_len = haystack.length(); int n_len = needle.length(); int rel = -1; if(h_len < n_len) return rel; if(haystack == needle || needle == "") return 0; for(int i = 0; i <= h_len - n_len; i++) { for(int k = 0, j = i; k < n_len && j < h_len; k++, j++) { if(haystack[j] != needle[k]) break; else if(k == n_len - 1) return i; } } return rel; }};

代碼二:把上面的代碼精簡(jiǎn)一下。

class Solution {public: int strStr(string haystack, string needle) { int m = haystack.length(), n = needle.length(); if (!n) return 0; for (int i = 0; i < m - n + 1; i++) { int j = 0; for (; j < n; j++) if (haystack[i + j] != needle[j]) break; if (j == n) return i; } return -1; }};

當(dāng)然在尋找子串方面,KMP是最經(jīng)典的算法。 使用KMP尋找子串可以得到:

class Solution {public: int strStr(string haystack, string needle) { int m = haystack.length(), n = needle.length(); if (!n) return 0; vector<int> lps = kmpPRocess(needle); for (int i = 0, j = 0; i < m; ) { if (haystack[i] == needle[j]) { i++; j++; } if (j == n) return i - j; if (i < m && haystack[i] != needle[j]) { if (j) j = lps[j - 1]; else i++; } } return -1; }private: vector<int> kmpProcess(string& needle) { int n = needle.length(); vector<int> lps(n, 0); for (int i = 1, len = 0; i < n; ) { if (needle[i] == needle[len]) lps[i++] = ++len; else if (len) len = lps[len - 1]; else lps[i++] = 0; } return lps; }};

KMP算法的介紹:

http://jakeboxer.com/blog/2009/12/13/the-knuth-morris-pratt-algorithm-in-my-own-Words/ http://www.geeksforgeeks.org/searching-for-patterns-set-2-kmp-algorithm/ BOOK: Introduction to Algorithm


上一篇:delegate vs event

下一篇:KMP探索

發(fā)表評(píng)論 共有條評(píng)論
用戶(hù)名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 庐江县| 洪湖市| 弥渡县| 乐至县| 永寿县| 页游| 剑阁县| 洪江市| 阿勒泰市| 闽侯县| 登封市| 公安县| 兰考县| 乌兰浩特市| 峨山| 都安| 农安县| 鄯善县| 贵南县| 新乐市| 邛崃市| 吉隆县| 方城县| 桦甸市| 浦县| 景宁| 大石桥市| 吉隆县| 泸西县| 民丰县| 荃湾区| 中西区| 隆安县| 乃东县| 广宁县| 固原市| 双辽市| 信丰县| 富顺县| 丹寨县| 汾西县|