LeetCode-in-Java

2744. Find Maximum Number of String Pairs

Easy

You are given a 0-indexed array words consisting of distinct strings.

The string words[i] can be paired with the string words[j] if:

Return the maximum number of pairs that can be formed from the array words.

Note that each string can belong in at most one pair.

Example 1:

Input: words = [“cd”,”ac”,”dc”,”ca”,”zz”]

Output: 2

Explanation: In this example, we can form 2 pair of strings in the following way:

It can be proven that 2 is the maximum number of pairs that can be formed.

Example 2:

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

Output: 1

Explanation: In this example, we can form 1 pair of strings in the following way:

It can be proven that 1 is the maximum number of pairs that can be formed.

Example 3:

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

Output: 0

Explanation: In this example, we are unable to form any pair of strings.

Constraints:

Solution

public class Solution {
    private boolean func(String a, String b) {
        int n = a.length();
        int m = b.length();
        if (n != m) {
            return false;
        }
        for (int i = 0; i < n; i++) {
            if (a.charAt(i) != b.charAt(n - 1 - i)) {
                return false;
            }
        }
        return true;
    }

    public int maximumNumberOfStringPairs(String[] words) {
        int ans = 0;
        int n = words.length;
        for (int i = 0; i < n - 1; i++) {
            for (int j = i + 1; j < n; j++) {
                if (func(words[i], words[j])) {
                    ans++;
                }
            }
        }
        return ans;
    }
}