實現?strStr()?函數。
給定一個?haystack 字符串和一個 needle 字符串,在 haystack 字符串中找出 needle 字符串出現的第一個位置 (從0開始)。如果不存在,則返回??-1。
示例 1:
輸入: haystack = "hello", needle = "ll"
輸出: 2
示例 2:輸入: haystack = "aaaaa", needle = "bba"
輸出: -1
說明:當?needle?是空字符串時,我們應當返回什么值呢?這是一個在面試中很好的問題。
對于本題而言,當?needle?是空字符串時我們應當返回 0 。這與C語言的?strstr()?以及 Java的?indexOf()?定義相符。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/implement-strstr
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。
解法:
?
class Solution {
public:vector<int> getnext(string str){int len = str.size();vector<int> next;next.push_back(-1);//next數組初值為-1int j = 0, k = -1;while (j < len - 1){if (k == -1 || str[j] == str[k])//str[j]后綴 str[k]前綴{j++;k++;next.push_back(k);}else{k = next[k];}}return next;}int strStr(string haystack, string needle) {if (needle.empty())return 0;int i = 0;//源串int j = 0;//子串int len1 = haystack.size();int len2 = needle.size();vector<int> next;next = getnext(needle);while ((i < len1) && (j < len2)){if ((j == -1) || (haystack[i] == needle[j])){i++;j++;}else{j = next[j];//獲取下一次匹配的位置}}if (j == len2)return i - j;return -1;}
};
?