459. (KMP) asks if a string is composed of patterns repeating repeated Substring pattern

Source: Internet
Author: User


Assuming that the STR length is Len and the repeating substring length is k, then if it is true that a string of multiple consecutive lengths of K is repeated to form STR, then when the next is obtained for STR, the continuous symmetry (the equal of the strings in the front and back of the two dashed boxes) will start from next[k+1]. Increment , until Next[len]=len-k, and (len-k)%k==0, indicating an integral number of K

Always ask for Next[len] instead of next[len-1], because next[len-1] simply represents the inner symmetry of the first len-1 letters, without taking into account the last letter that str[len-1]

So the solution is very simple: first the next array of STR, always find Next[len], and then see if Next[len] is not 0 and divisible by K (K=len-next[len])



  
 
  1. public class Solution {
  2. public bool RepeatedSubstringPattern(string str) {
  3. int length = str.Length;
  4. int[] next = new int[length+1];//length+1 求最大公共元素长度数组
  5. next[0] = -1;
  6. int j = 0;
  7. int k = -1;
  8. while (j < length) {
  9. if (k == -1 || str[j] == str[k]) {
  10. ++j;
  11. ++k;
  12. next[j] = k;
  13. } else {
  14. k = next[k];
  15. }
  16. }
  17. return [ length ] != 0 && next [ Span class= "PLN" >length ] % Span class= "PLN" > ( length - Span class= "PLN" > next [ length ) == 0 Span class= "pun";
  18. }
  19. }



From for notes (Wiz)

459. (KMP) asks if a string is composed of patterns repeating repeated Substring pattern

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.