3805. Count Caesar Cipher Pairs
Description
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.
- Choose either
sort. - Replace every letter in the chosen string with the next letter in the alphabet cyclically. The next letter after
'z'is'a'.
Count the number of pairs of indices (i, j) such that:
i < jwords[i]andwords[j]are similar.
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.
"fusion""gvtjpo""hwukqp""ixvlrq""jywmsr""kzxnts""layout"
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:
1 <= n == words.length <= 1051 <= m == words[i].length <= 1051 <= n * m <= 105words[i]consists only of lowercase English letters.
Solutions
Solution 1: String Transformation + Counting
We can transform each string into a unified form. Specifically, we convert the first character of the string to 'z', and then transform the other characters in the string with the same offset. This way, all similar strings will be transformed into the same form. We use a hash table \(\textit{cnt}\) to record the number of occurrences of each transformed string.
Finally, we iterate through the hash table, calculate the combination number \(\frac{v(v-1)}{2}\) for each string's occurrence count \(v\), and add it to the answer.
The time complexity is \(O(n \times m)\) and the space complexity is \(O(n \times m)\), where \(n\) is the length of the string array and \(m\) is the length of the strings.
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |