LeetCode2744. Find Maximum Number of String Pairs

一、题目

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:

The string words[i] is equal to the reversed string of words[j].
0 <= i < j < words.length.
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:

  • We pair the 0th string with the 2nd string, as the reversed string of word[0] is “dc” and is equal to words[2].
  • We pair the 1st string with the 3rd string, as the reversed string of word[1] is “ca” and is equal to words[3].
    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:

  • We pair the 0th string with the 1st string, as the reversed string of words[1] is “ab” and is equal to words[0].
    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:

1 <= words.length <= 50
words[i].length == 2
words consists of distinct strings.
words[i] contains only lowercase English letters.

二、题解

class Solution {
public:
    int maximumNumberOfStringPairs(vector<string>& words) {
        int n = words.size();
        int res = 0;
        for(int i = 0;i < n;i++){
            for(int j = i + 1;j < n;j++){
                string s1 = words[i],s2 = words[j];
                if(s1[0] == s2[1] && s1[1] == s2[0]) res++;
            }
        }
        return res;
    }
};
  • 23
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值