题目描述:
给定一个目标串str和模式串ptr,要求寻找ptr第一次在str出现的位置,并返回其下标,匹配不到则返回-1。
暴力匹配(Brute force)
暴力匹配的思路很简单,开始时用模式串ptr从匹配串str的第一个字符开始向后匹配,当出现不同字符时,从匹配串str的下一个字符开始重新匹配,即原搜索位置+1开始重新匹配。
空间复杂度:O(1);
时间复杂度:O(N*M),N是目标串的长度,M是模式串的长度;
代码如下:
int strStr(string haystack, string needle) {
//异常处理
if (haystack.length() == 0)
{
if (needle.length() == 0)
{
return 0;
}
else
{
return -1;
}
}
else if (haystack.length() < needle.length())
{
return -1;
}
int p1; //p1是目标串的当前匹配位置
int p2; //p2是模式串的当前匹配位置
int i = needle.length();//将i置为目标串中的匹配串最后一个字符对应的位置
for (p1 = 0; i <= haystack.length(); ++i)
{
int p1_old = p1;//记录这一轮匹配的初始位置
p2 = 0;//每一次都从模式串的第一位开始
while (p1 < haystack.length() && p2 < needle.length() && haystack[p1] == needle[p2])
{
++p1;
++p2;
}
//匹配成功则返回下标
if (p2 >= needle.length())
{
return p1_old;
}
p1 = p1_old + 1; //从原搜索位置+1继续搜索
}
return -1;
}