KMP string pattern matching algorithm

Source: Internet
Author: User

Overview

?? KMP algorithm I think there are two key points: 1. Calculate a partial match table for a pattern string (at this point, compare yourself to yourself) 2. When the main string is matched, the main string is only traversed once, and the matching table calculates where the pattern string should move, depending on the part of the pattern string. The time complexity of the KMP algorithm is O (m+n); The algorithm code (PHP) I implemented below

theory

About the KMP theory section, this article is well written: http://kb.cnblogs.com/page/176818/. I will not dwell on it.

calculate partial Match table
 function kmp_next($string){    $length= Strlen ($string);//Get string length    $next[0] =0;$j=0;$i=1; while($i<$length){if($string{$j} ==$string{$i}){$j++;$next[$i]=$j;$i++; }Else if($j==0){$next[$i] =$j;$i++; }Else{$j=$next[$j]; }    }return $next;}
KMP Algorithm
 function kmp($text,$mode){    $t _length= Strlen ($text);$m _length= Strlen ($mode);if($t _length<$m _length){return-1; }$arr= Kmp_next ($mode);$j=0;$i=0; while($i<$t _length){if($text{$i}==$mode{$j}){if($j<$m _length-1){$j++;$i++; }Else{return $i-$m _length+1; }        }Else if($j==0){$i++; }Else{$j=$arr[$j-1]; }    }return-1;}
called
$string‘BBC ABCDAB ABCDABCDABDE‘;$mode‘ABCDABD‘;$key = kmp($string,$mode);var_dump(kmp_next($mode));var_dump($key);var_dump(substr($string,$key,strlen($mode)));
Results

KMP string pattern matching algorithm

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.