PAT C语言入门题目-6-4 查找子串 (20 分)

6-4 查找子串 (20 分)

本题要求实现一个字符串查找的简单函数。

函数接口定义:

char *search( char *s, char *t );

函数search在字符串s中查找子串t,返回子串t在s中的首地址。若未找到,则返回NULL。

裁判测试程序样例:

#include <stdio.h>
#define MAXS 30

char *search(char *s, char *t);
void ReadString( char s[] ); /* 裁判提供,细节不表 */

int main()
{
    char s[MAXS], t[MAXS], *pos;

    ReadString(s);
    ReadString(t);
    pos = search(s, t);
    if ( pos != NULL )
        printf("%d\n", pos - s);
    else
        printf("-1\n");

    return 0;
}

/* 你的代码将被嵌在这里 */

输入样例1:

The C Programming Language
ram

输出样例1:

10

输入样例2:

The C Programming Language
bored

输出样例2:

-1
char *search(char *s, char *t)
{
    char *pos=s; // pos值为每次比较主串的开始处
    char *p=pos, *q=t;
    while(*pos){
        while(*q){
            if(*p == *q){
                p++;
                q++;
            }
            else
                break; // 子串虽未遍历完,但已遇到不等的字符
        }
        if( (*p != *q)&&(*q) ){
        // 内循环因字符不等而退出,且子串未走到结束标志处,继续比较
            pos++;
            p = pos;
            q = t;
        }
        else
            break; // 已找到,跳出外循环
    }
    if(*pos=='\0') // 若外循环因主串走到结束标志处而退出,则未找到
        pos = NULL;
    return pos;
}

KMP算法: 

void cal_next(char *str, int *next, int len)
{
    next[0] = -1;//next[0]初始化为-1,-1表示不存在相同的最大前缀和最大后缀
    int k = -1;//k初始化为-1
    for (int q = 1; q <= len-1; q++)
    {
        while (k > -1 && str[k + 1] != str[q])//如果下一个不同,那么k就变成next[k],注意next[k]是小于k的,无论k取任何值。
        {
            k = next[k];//往前回溯
        }
        if (str[k + 1] == str[q])//如果相同,k++
        {
            k = k + 1;
        }
        next[q] = k;//这个是把算的k的值(就是相同的最大前缀和最大后缀长)赋给next[q]
    }
}
char *search(char *s ,char *t)
{
    slen=strlen(s);
    tlen=strlen(t);
    int *next = new int[plen];
    cal_next(t, next, plen);//计算next数组
    int k = -1;
    for (int i = 0; i < slen; i++)
    {
        while (k >-1&& t[k + 1] != s[i])//ptr和str不匹配,且k>-1(表示ptr和str有部分匹配)
            k = next[k];//往前回溯
        if (t[k + 1] == s[i])
            k = k + 1;
        if (k == plen-1)//说明k移动到ptr的最末端
        {
            //cout << "在位置" << i-plen+1<< endl;
            //k = -1;//重新初始化,寻找下一个
            //i = i - plen + 1;//i定位到该位置,外层for循环i++可以继续找下一个(这里默认存在两个匹配字符串可以部分重叠),感谢评论中同学指出错误。
            return *(i-plen+1);//返回相应的位置
        }
    }
    return NULL;  
}

猜你喜欢

转载自blog.csdn.net/qq_37503890/article/details/86601323