fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int * Z_algo(string s,int n){
  5. int *z=new int[n];
  6. int l=0,r=0;
  7.  
  8. for(int i=1;i<n;i++){
  9. //condition 1
  10. if(i>r){
  11. l=i;
  12. r=i;
  13. while(r<n and s[r-l]==s[r]){
  14. r++;
  15. }
  16. r--;
  17. z[i]=r-l+1;
  18.  
  19. }
  20. //condition 2
  21. else{
  22. int j=i-l;
  23.  
  24. //condition 2a
  25. if(z[j]<r-i+1){
  26. z[i]=z[j];
  27. }
  28. //condition 2b
  29. else{
  30. l=i;
  31. while(r<n and s[r-l]==s[r]){
  32. r++;
  33. }
  34. r--;
  35. z[i]=r-l+1;
  36. }
  37. }
  38. }
  39. return z;
  40. }
  41.  
  42. int main(){
  43. string s="abc$abcdabcfabdabe";
  44. int n=s.size();
  45. int *z=Z_algo(s,n);
  46. for(int i=1;i<n;i++){
  47. cout<<z[i]<<" ";
  48. }
  49. cout<<endl;
  50. return 0;
  51. }
  52.  
Success #stdin #stdout 0s 4192KB
stdin
Standard input is empty
stdout
0 0 0 3 0 0 0 3 0 0 0 2 0 0 2 0 0