String Matching(模式匹配)

题目描述

    Finding all occurrences of a pattern in a text is a problem that arises frequently in text-editing programs.     Typically,the text is a document being edited,and the pattern searched for is a particular word supplied by the user.       We assume that the text is an array T[1..n] of length n and that the pattern is an array P[1..m] of length m<=n.We further assume that the elements of P and  T are all alphabets(∑={a,b...,z}).The character arrays P and T are often called strings of characters.       We say that pattern P occurs with shift s in the text T if 0<=s<=n and T[s+1..s+m] = P[1..m](that is if T[s+j]=P[j],for 1<=j<=m).       If P occurs with shift s in T,then we call s a valid shift;otherwise,we calls a invalid shift.      Your task is to calculate the number of vald shifts for the given text T and p attern P.

输入描述:

   For each case, there are two strings T and P on a line,separated by a single space.You may assume both the length of T and P will not exceed 10^6.

输出描述:

    You should output a number on a separate line,which indicates the number of valid shifts for the given text T and pattern P.
示例1

输入

abababab abab

输出

3

代码如下:利用strstr函数

strchr函数原型:char * strchr(char * str, int ch); 功能就是找出在字符串str中第一次出项字符ch的位置,找到就返回该字符位置的指针(也就是返回该字符在字符串中的地址的位置),找不到就返回空指针(就是 null)。

C语言函数

编辑
包含文件: string.h
函数名: strstr
函数原型:
     extern char *strstr(char *str1, const char *str2);
语法:
* strstr(str1,str2)
str1: 被查找目标 string expression to search.
str2: 要查找对象 The string expression to find.
返回值:若str2是str1的子串,则返回str2在str1的首次出现的地址;如果str2不是str1的子串,则返回NULL。

#include <stdio.h>
#include <string.h>
#include<math.h>
#include<stdlib.h>

int main(){
    int n;
    char a[1000005],b[1000005];

    while(scanf("%s %s",a,b)!=EOF){
        char *s=a;
        n=0;
        while(s=strstr(s,b)){
            s++;
            n++;
        }
        printf("%d\n",n);
    }
    return 0;
}

方法二:蛮力匹配法

#include <stdio.h>
#include <string.h>
#include<math.h>
#include<stdlib.h>

int main(){
    int n;
    char a[1000005],b[1000005];

    while(scanf("%s %s",a,b)!=EOF){
        int lena=strlen(a),lenb=strlen(b),i,j;
        n=0;
        for(i=0;i<=lena-lenb;i++){
                int flag=1;
            for(j=0;j<lenb;j++)
                if(a[i+j]!=b[j]){
                    flag=0;
                    break;
                }
            if(flag==1)
                n++;
        }
        printf("%d\n",n);
    }
    return 0;
}


猜你喜欢

转载自blog.csdn.net/qq_31342997/article/details/80302074
今日推荐