1. 程式人生 > >String Matching(模式匹配)

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;
}