Fortune left France advanced classes 1_1 add character to get at least N times the original character


Problem:
  Given a string str1, str1 can only add character to the back becomes str2.

  Requirements 1: str2 str1 must contain two, there may be two str1 overlap, but can not begin with the same position.

  Requirement 2: str2 as short as possible eventual return str2

  For example:

    str1 = 123, str2 = 123123, the str1 comprising two, not beginning at the same position, and the shortest str2.

    str1 = 123123, str2 = 123123123 When, comprising two str1, does not begin at the same position, and the shortest str2.

    str1 = 111, str2 = 1111. str1 comprising two, does not start with the same position and the shortest str2.

 

Solution:
  Use KMP algorithm;

  After the last character of seeking a longest space length before the same suffix, then the foregoing character that is not part of the same adding N times on the line

 

Code:

  

 1 #pragma once
 2 #include <iostream>
 3 #include <vector>
 4 #include <string>
 5 
 6 using namespace std;
 7 
 8 void getIndex(int*& index, string str)
 9 {
10     for (int i = 0, p = 0; i <= str.length(); ++i)
11     {
12         if (i == 0)
13             index[i] = -1;
14         else if (i == 1)
15             index[i] = 0;
16         else
17         {
18             if (str[i - 1] == str[p])
19                 index[i] = ++p;
20             else if (p > 0)
21                 p = index[p];
22             else
23                 index[i] = 0;
24         }
25     }
26 }
27 
28 String addstr ( String STR, int N)
 29  {
 30      String RES = STR;
 31 is      int * index = new new  int [str.size () + . 1 ];
 32      getIndex (index, STR); // Get the maximum angle of the prefix and suffix standard 
33 is  
34 is      int L = str.length () - index [str.length ()]; // prefix and suffix length of the last position of 
35      for ( int I = . 1 ; I <N; ++ I)
 36      {
 37 [          for ( int J = 0; j < L; ++j)
38             res += str[j];
39     }
40     delete[] index;
41     return res;
42 }
43 
44 
45 void Test()
46 {
47     string str;
48     str = "abcabc";
49     cout << addStr(str, 3) << endl;
50 
51     str = "12345";
52     cout << addStr(str, 2) << endl;
53 }

 

Guess you like

Origin www.cnblogs.com/zzw1024/p/11029620.html