forked from sherwin2000/Hackerrank-pgms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathString Similarity.cpp
35 lines (35 loc) · 1019 Bytes
/
String Similarity.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
int main(){
int t ;
cin >> t;
string s;
while(t--){
cin >> s ;
ll len = s.size() ;
int z[len] = {0} ;
int left = 0 , right = 0 ;
for(int i = 1 ; i < len ; i++){
if(i > right){
left = right = i;
while(right < len and (s[right] == s[right - left]))
right++;
z[i] = right-left;
right--;
} else {
int k = i - left; // do a mistake here.
if(z[k] < (right-i+1)){
z[i] = z[k];
} else {
left = i;
while(right < len and (s[right] == s[right-left]))
right++;
z[i] = right-left;
right--;
}
}
}
cout << accumulate(z,z+len,len) << endl;
}
}