目录
【朴素匹配——找到首位相同字符,截取相同长度字符串,进行比较】
【题目描述】
实现 strStr() 函数。
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回 -1 。
说明:
当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与 C 语言的 strstr() 以及 Java 的 indexOf() 定义相符。
【题目示例】
输入:haystack = "hello", needle = "ll"
输出:2
输入:haystack = "aaaaa", needle = "bba"
输出:-1
【朴素匹配——找到首位相同字符,截取相同长度字符串,进行比较】
【思路如下】
循环遍历haystack数组每一位,直到找到与needle的第一个字符相同的字符时,截取出haystack从 i 开始的与needle相同长度的一段字符串,与needle进行比较,如果相同则返回 i ,否则继续查找,如果到最后没有找到,那么返回-1。
时间复杂度为:O(m*(n-m))
空间复杂度为:O(m)
【采用代码如下】
class Solution {
public:
int strStr(string haystack, string needle) {
int len1=haystack.length();
int len2=needle.length();
for(int i=0;i<len1;i++)
{
if(haystack[i]==needle[0])
{
string str;
for(int j=i;(j<(i+len2))&&(j<len1);j++)//这里注意j的判定条件,
//小心数组下标越界
str+=haystack[j];
if(str==needle)
return i;
}
}
return -1;
}
};
【KMP算法】
本题是经典的字符串单模匹配的模型,因此可以用字符串匹配算法来解决,这里采用Knuth-Morris-Pratt算法来解决。
class Solution {
public:
void getNext(int* next, const string& s) {
int j = 0;
next[0] = 0;
for(int i = 1; i < s.size(); i++) {
while (j > 0 && s[i] != s[j]) {
j = next[j - 1];
}
if (s[i] == s[j]) {
j++;
}
next[i] = j;
}
}
int strStr(string haystack, string needle) {
if (needle.size() == 0) {
return 0;
}
int next[needle.size()];
getNext(next, needle);
int j = 0;
for (int i = 0; i < haystack.size(); i++) {
while(j > 0 && haystack[i] != needle[j]) {
j = next[j - 1];
}
if (haystack[i] == needle[j]) {
j++;
}
if (j == needle.size() ) {
return (i - needle.size() + 1);
}
}
return -1;
}
};