数据结构课程设计2022夏7-1 jmu-ds-实现KMP

7-1 jmu-ds-实现KMP

给两个字符串A、B, 从A中找出第一次出现B的位置。

输入格式:

第一行输入一个整数n,表示测试数据的个数

对于每组测试数据,输入两个字符串S T,S和T中间用一个空格隔开,每组数据占一行。

输出格式:

对于每组测试数据,输出A中找出第一次出现B的位置,如果A不包含B,输出“not find!”

输入样例:

3
abcdabbcd abbc
abcd efg
abbcdd bbc
 

输出样例:

4
not find!
1
 
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
#include <stdio.h>
#include<string.h>
const int MAX  = 10000;
 
 
void get_next(char str[], int len, int next[])
{
    int i = 0, j = 0;
    next[0] = -1;
    for (i = 1; i < len; i++) {
        while (j > 0 && str[i] != str[j])
            j = next[j-1];
        if (str[i] == str[j]) j++;
        next[i] = j;
    }
}
 
 int find (char s[], int len_s, char t[], int len_t, int next[])
{
    int i = 0, j = 0;
    while(i < len_s && j < len_t)
    {
        //匹配字符        
        if( j ==-1 ||s[i] == t[j])
        {
            j++;
            i++;
            
        }
        else{
               j = next[j];
        }
    }
        
        if(j == len_t)
          return i - j ;
        else
           return -1;
    
}
 
int main()
{
    int cas,a;
    char s[MAX], t[MAX];
    int next[MAX];
    scanf("%d", &cas);
    while (cas --)
    {
        scanf("%s %s", s, t);
        int len_s = strlen(s);
        int len_t = strlen(t);
        get_next(t, len_t, next);
        a=find (s, len_s, t, len_t, next);
        if(a==-1)
        printf("not find!\n");
        else
        printf("%d\n", a);
    }
    return 0;
}

 

posted @ 2022-07-09 20:03  zrswheart  阅读(97)  评论(0编辑  收藏  举报