LeetCode-in-Java

3805. Count Caesar Cipher Pairs

Medium

You are given an array words of n strings. Each string has length m and contains only lowercase English letters.

Two strings s and t are similar if we can apply the following operation any number of times (possibly zero times) so that s and t become equal.

Count the number of pairs of indices (i, j) such that:

Return an integer denoting the number of such pairs.

Example 1:

Input: words = [“fusion”,”layout”]

Output: 1

Explanation:

words[0] = "fusion" and words[1] = "layout" are similar because we can apply the operation to "fusion" 6 times. The string "fusion" changes as follows.

Example 2:

Input: words = [“ab”,”aa”,”za”,”aa”]

Output: 2

Explanation:

words[0] = "ab" and words[2] = "za" are similar. words[1] = "aa" and words[3] = "aa" are similar.

Constraints:

Solution

import java.util.HashMap;
import java.util.Map;

public class Solution {
    public long countPairs(String[] words) {
        String[] a = words;
        Map<String, Integer> b = new HashMap<>();
        long c = 0;
        for (String d : a) {
            char[] e = d.toCharArray();
            int f = e[0];
            for (int g = 0; g < e.length; g++) {
                e[g] = (char) ((e[g] - f + 26) % 26);
            }
            String h = new String(e);
            int i = b.getOrDefault(h, 0);
            c += i;
            b.put(h, i + 1);
        }
        return c;
    }
}