LeetCode-in-Java

2506. Count Pairs Of Similar Strings

Easy

You are given a 0-indexed string array words.

Two strings are similar if they consist of the same characters.

Return the number of pairs (i, j) such that 0 <= i < j <= word.length - 1 and the two strings words[i] and words[j] are similar.

Example 1:

Input: words = [“aba”,”aabb”,”abcd”,”bac”,”aabc”]

Output: 2

Explanation: There are 2 pairs that satisfy the conditions:

Example 2:

Input: words = [“aabb”,”ab”,”ba”]

Output: 3

Explanation: There are 3 pairs that satisfy the conditions:

Example 3:

Input: words = [“nba”,”cba”,”dba”]

Output: 0

Explanation: Since there does not exist any pair that satisfies the conditions, we return 0.

Constraints:

Solution

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

public class Solution {
    public int similarPairs(String[] words) {
        int len = words.length;
        if (len == 1) {
            return 0;
        }
        byte[][] alPh = new byte[len][26];
        Map<String, Integer> map = new HashMap<>();
        for (int i = 0; i < len; i++) {
            String word = words[i];
            for (char c : word.toCharArray()) {
                int idx = c - 'a';
                if (alPh[i][idx] == 0) {
                    alPh[i][idx]++;
                }
            }
            String s = new String(alPh[i]);
            if (map.containsKey(s)) {
                map.put(s, map.get(s) + 1);
            } else {
                map.put(s, 1);
            }
        }
        int pairs = 0;
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            int freq = entry.getValue();
            if (freq > 1) {
                pairs += (freq * (freq - 1)) / 2;
            }
        }
        return pairs;
    }
}