String Similarity


Problem Statement :


For two strings A and B, we define the similarity of the strings to be the length of the longest prefix common to both strings. For example, the similarity of strings "abc" and "abd" is 2, while the similarity of strings "aaa" and "aaab" is 3.

Calculate the sum of similarities of a string S with each of it's suffixes.

Input Format

The first line contains the number of test cases t.
Each of the next t lines contains a string to process, s.

Constraints

1  <=  t  <=  10
1   <=   | s  |  <=   100000
s is composed of characters in the range ascii[a-z]


Output Format

Output t lines, each containing the answer for the corresponding test case.

Sample Input

2
ababaa  
aa


Sample Output

11  
3



Solution :



title-img


                            Solution in C :

In    C++  :








#include <algorithm>
#include <string>
#include <vector>
#include <queue>
#include <iostream>
#include <cmath>
#include <sstream>
#include <map>
#include <set>
#include <numeric>
#include <memory.h>
#include <cstdio>
#include <assert.h>
#include <numeric>

using namespace std;

#define pb push_back
#define INF 1011111111
#define FOR(i,a,b) for (int _n(b), i(a); i < _n; i++)
#define rep(i,n) FOR(i,0,n)
#define ford(i,a,b) for(int i=(a),_b=(b);i>=_b;--i)
#define CL(a,v) memset((a),(v),sizeof(a))
#define mp make_pair
#define X first
#define Y second
#define all(c) (c).begin(), (c).end()
#define SORT(c) sort(all(c))

typedef long long ll;
typedef vector<int> VI;
typedef pair<int,int> pii;

vector<ll> z_func(const string &s)
{
    int n = s.size();
    vector<ll> z(n,0);
    int l = 0,r = 0;

    FOR(i,1,n)
    {
        if(i <= r)
            z[i] = min(z[i-l], (ll)r-i+1);

        while(i+z[i] < n && s[i+z[i]] == s[z[i]]) z[i] ++;

        if(i+z[i]-1 > r)
            r = i+z[i]-1, l = i;
    }

    return z;
}

int main()
{
	#ifndef ONLINE_JUDGE
        //freopen("input.txt","r",stdin);
        //freopen("output.txt","w",stdout);
	#endif

    int T;
    cin >> T;

    while(T--)
    {
        string s;
        cin >> s;

        vector<ll> z = z_func(s);

        cout << 1LL*s.size() + accumulate(all(z), 0LL) << endl;
    }

	return 0;
}









In   Java   :







import java.util.Scanner;


public class Solution {

	private String[] strArray;
	
	public boolean read(){
		
		Scanner sc = new Scanner(System.in);
		int n = Integer.valueOf(sc.nextLine());
		strArray = new String[n];
		int i = 0;
		while(i < n){
			
			strArray[i++] = sc.nextLine();
		}
		
		return true;
	}
	
	public void solve(){
		
    	for(String s : strArray){
	    	int len = s.length();
	    	int sum = len;
	    	for(int i=1; i<len;i++){
	    		int count = 0;
	    		for(int j=0,k=i; j<len && k<len; j++,k++){
	    			  if(s.charAt(k) == s.charAt(j)){
	    				  count++;
	    			  }else{
	    				  break;
	    			  }
	    		}
	    		sum = sum + count;
	    	}
	    	System.out.println(sum);
    	}
    	
	}
	public void solveIt(){
		
    	for(String s : strArray){
	    	int len = s.length();
	    	long sum = len;
	    	char ch = s.charAt(0);
	    	int pos = s.indexOf(ch, 1);	    	
	    	while(pos != -1){
	    		long count = 1;
	    		for(int j=1,k=pos+1; j<len && k<len; j++,k++){
	    			  if(s.charAt(k) == s.charAt(j)){
	    				  count++;
	    			  }else{
	    				  break;
	    			  }
	    		}
	    		sum = sum + count;
	    		pos = s.indexOf(ch, pos+1);
	    	}
	    	System.out.println(sum);
    	}
    	
	}

	public void solveZ(){
		
    	for(String s : strArray){
	    	int len = s.length();
	    	long sum = len;
	    	int[] z = new int[len];
	    	int l=0,r=0;
	    	for(int k=1;k<len;k++){
	    		int j;
	    		if(k < r){
	    			j = ((r-k) < z[k-l] )? (r-k) : z[k-l];
	    		}else{
	    			j = 0;
	    		} 
	    		while(k+j < len){
	    			
	    			if(s.charAt(k+j) == s.charAt(j)){
	    				j++;
	    			}else{
	    				break;
	    			}
	    		}
	    		z[k] = j;
	    		sum = sum + z[k];
	    		if(k+j > r){
	    			l = k;
	    			r= k+j;
	    		}

	    	}
	    	System.out.println(sum);
    	}
    	
	}
	

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Solution s = new Solution();
		if(s.read()){
			s.solveZ();
		}
		
	}

}








In    C  :







#include <stdio.h>
#include <string.h>

#define N 200000
char str[N];
int pre[N];
int len[N];

int main() {
	int tc;
	scanf("%d", &tc);
	while (tc --) {
		memset(pre, -1 , sizeof(pre));
		memset(len, 0, sizeof(len));
		scanf("%s", str);
		int n = strlen(str);
		long long sum = 0;
		int k = -1;
		int pos = 0;
		while (pos + 1 < n) {
			if (str[k + 1] == str[pos + 1]) {
				k++; pos++;
				pre[pos] = k;
				len[pos - k] = k + 1;
			} else if (k == -1) {
				pos++;
			} else {
				k = pre[k];
				len[pos - k] = k + 1;
			}
		}
		while (k > 0) {
			k = pre[k];
			len[pos - k] = k + 1;
		}
		len[0] = n;
		for (int i = 0; i < n; i++) {
			sum += len[i];
		}

		for (int i = 0; i < n; i++) {
			if (len[i] == 0) {
				for (int j = 0; i + j < n; j++) {
					if (str[j] == str[i+j]) {
						sum++;
					} else {
						break;
					}
				}
			}
		}
		printf("%lld\n", sum);
	}
}









In    Python3  :






def z(w, T):
    T.append(len(w))
    l = r = 0
    for i in range(1, len(w)):
        k = 0
        if i < r:
            k = min(r-i, T[i-l])
        while i+k<len(w) and w[i+k] == w[k]:
            k += 1
        T.append(k)
        if i+k > r:
            l = i
            r = i+k

N = int(input())
for i in range(N):
    curr = input()
    count = 0
    T = []
    z(curr, T)
    for j in range(len(T)):
        count += T[j]
    print(count)
                        








View More Similar Problems

Reverse a linked list

Given the pointer to the head node of a linked list, change the next pointers of the nodes so that their order is reversed. The head pointer given may be null meaning that the initial list is empty. Example: head references the list 1->2->3->Null. Manipulate the next pointers of each node in place and return head, now referencing the head of the list 3->2->1->Null. Function Descriptio

View Solution →

Compare two linked lists

You’re given the pointer to the head nodes of two linked lists. Compare the data in the nodes of the linked lists to check if they are equal. If all data attributes are equal and the lists are the same length, return 1. Otherwise, return 0. Example: list1=1->2->3->Null list2=1->2->3->4->Null The two lists have equal data attributes for the first 3 nodes. list2 is longer, though, so the lis

View Solution →

Merge two sorted linked lists

This challenge is part of a tutorial track by MyCodeSchool Given pointers to the heads of two sorted linked lists, merge them into a single, sorted linked list. Either head pointer may be null meaning that the corresponding list is empty. Example headA refers to 1 -> 3 -> 7 -> NULL headB refers to 1 -> 2 -> NULL The new list is 1 -> 1 -> 2 -> 3 -> 7 -> NULL. Function Description C

View Solution →

Get Node Value

This challenge is part of a tutorial track by MyCodeSchool Given a pointer to the head of a linked list and a specific position, determine the data value at that position. Count backwards from the tail node. The tail is at postion 0, its parent is at 1 and so on. Example head refers to 3 -> 2 -> 1 -> 0 -> NULL positionFromTail = 2 Each of the data values matches its distance from the t

View Solution →

Delete duplicate-value nodes from a sorted linked list

This challenge is part of a tutorial track by MyCodeSchool You are given the pointer to the head node of a sorted linked list, where the data in the nodes is in ascending order. Delete nodes and return a sorted list with each distinct value in the original list. The given head pointer may be null indicating that the list is empty. Example head refers to the first node in the list 1 -> 2 -

View Solution →

Cycle Detection

A linked list is said to contain a cycle if any node is visited more than once while traversing the list. Given a pointer to the head of a linked list, determine if it contains a cycle. If it does, return 1. Otherwise, return 0. Example head refers 1 -> 2 -> 3 -> NUL The numbers shown are the node numbers, not their data values. There is no cycle in this list so return 0. head refer

View Solution →