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.
s or t.'z' is 'a'.Count the number of pairs of indices (i, j) such that:
i < jwords[i] and words[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.class Solution {
fun countPairs(words: Array<String>): Long {
val a = words
val b: MutableMap<String?, Int?> = HashMap<String?, Int?>()
var c: Long = 0
for (d in a) {
val e = d.toCharArray()
val f = e[0].code
for (g in e.indices) {
e[g] = ((e[g].code - f + 26) % 26).toChar()
}
val h = String(e)
val i: Int = b.getOrDefault(h, 0)!!
c += i.toLong()
b.put(h, i + 1)
}
return c
}
}