KMP Simple Application

Source: Internet
Author: User

The topic describes whether string2 is a substring of string1 given two strings string1 and string2. Input input contains multiple sets of data, each set of test data contains two lines, the first row represents string1 (length less than 1000000), the second line represents string2 (length less than 1000000), string1 and string2 ensure that no spaces appear. Output for each set of input data, if string2 is a string1 substring, the output string2 in string1 position, if not, output-1. Sample input
Abca12345645abcddd
Sample output
14-1

This is also a simple KMP algorithm, and learn the password must be the same as the program, but there is a word in this topic is to ensure that two strings do not appear space, so the input string should be used scanf ("%s", S1);

And can not use gets (S1), if use gets the words will always WA;

#include <stdio.h> #include <string.h> #define N 1000001char s1[n],s2[n];int next[n];void getnext () {  int i=0,j=-1;   Next[0]=-1;   while (s2[i]!= ')   {     if (J==-1 | | s2[i]==s2[j])     {       i++;       j + +;       next[i]=j;     }     else     j=next[j];}   } void KMP () {  int i=0,j=0;  GetNext ();  int Len1=strlen (s1);  int Len2=strlen (s2);  while (I<len1 && j<len2)  {    if (J==-1 | | s1[i]==s2[j])    {      i++;      j + +;    }    else    j=next[j];  }  if (j>=len2)  {    printf ("%d\n", i-len2+1);  }  else  {    printf (" -1\n");}  } int main () {while  (~scanf ("%s", S1))  {    scanf ("%s", S2);    KMP ();  }  return 0;}


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

KMP Simple Application

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.