String Similarity

  • + 0 comments

    import java.util.Scanner;

    public class StringSimilarity { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int t = scanner.nextInt(); // Number of test cases scanner.nextLine(); // Consume newline

        while (t-- > 0) {
            String s = scanner.nextLine(); // Input string
            int[] z = zFunction(s);
            long sum = 0;
    
            for (int i = 0; i < s.length(); i++) {
                sum += z[i];
            }
    
            System.out.println(sum); // Output sum of similarities
        }
    
        scanner.close();
    }
    
    // Function to compute Z array for a given string
    private static int[] zFunction(String s) {
        int n = s.length();
        int[] z = new int[n];
        z[0] = n;
        int l = 0, r = 0;
    
        for (int i = 1; i < n; i++) {
            if (i <= r) {
                z[i] = Math.min(r - i + 1, z[i - l]);
            }
    
            while (i + z[i] < n && s.charAt(z[i]) == s.charAt(i + z[i])) {
                z[i]++;
            }
    
            if (i + z[i] - 1 > r) {
                l = i;
                r = i + z[i] - 1;
            }
        }
    
        return z;
    }
    

    }