力扣刷题第三天 最大字符串配对数目

题目描述:

给你一个下标从 0 开始的数组 words ,数组中包含 互不相同 的字符串。

如果字符串 words[i] 与字符串 words[j] 满足以下条件,我们称它们可以匹配:

  • 字符串 words[i] 等于 words[j] 的反转字符串。
  • 0 <= i < j < words.length

请你返回数组 words 中的 最大 匹配数目。

注意,每个字符串最多匹配一次。

解法一:枚举

二重循环,枚举给定的数组 words 中的 words[i] 和 words[j]是否可以匹配

cpp 复制代码
class Solution {
public:
    int maximumNumberOfStringPairs(vector<string>& words) {
        int n = words.size();
        int ans = 0;
        for (int i = 0; i < n; ++i) {
            for (int j = i + 1; j < n; ++j) {
                if (words[i][0] == words[j][1] && words[i][1] == words[j][0]) {
                    ++ans;
                }
            }
        }
        return ans;
    }
};
解法二:哈希集合

借助哈希集合,使用vector和set容器解决问题

cpp 复制代码
class Solution {
public:
    int maximumNumberOfStringPairs(vector<string>& words) {
        int n = words.size();
        int ans = 0;
        unordered_set<int> seen;
        for (int i = 0; i < n; ++i) {
            if (seen.count(words[i][1] * 100 + words[i][0])) {
                ++ans;
            }
            seen.insert(words[i][0] * 100 + words[i][1]);
        }
        return ans;
    }
};
解法三:哈希通用解法,字符串长度可以随意
cpp 复制代码
class Solution {
public:
   int maximumNumberOfStringPairs(vector<string>& words) {
       int ans = 0;
       unordered_set<string> occ;
       for (auto& word : words) {
           string tmp = word;
           reverse(tmp.begin(), tmp.end());
           if (occ.count(tmp)) {
               ans++;
           }
           occ.insert(word);
       }
       return ans;
   }
};
相关推荐
数智工坊36 分钟前
【数据结构-树与二叉树】4.6 树与森林的存储-转化-遍历
数据结构
晚霞的不甘1 小时前
Flutter for OpenHarmony 可视化教学:A* 寻路算法的交互式演示
人工智能·算法·flutter·架构·开源·音视频
望舒5131 小时前
代码随想录day25,回溯算法part4
java·数据结构·算法·leetcode
独好紫罗兰1 小时前
对python的再认识-基于数据结构进行-a006-元组-拓展
开发语言·数据结构·python
C++ 老炮儿的技术栈1 小时前
Qt 编写 TcpClient 程序 详细步骤
c语言·开发语言·数据库·c++·qt·算法
KYGALYX1 小时前
逻辑回归详解
算法·机器学习·逻辑回归
铉铉这波能秀1 小时前
LeetCode Hot100数据结构背景知识之集合(Set)Python2026新版
数据结构·python·算法·leetcode·哈希算法
参.商.1 小时前
【Day 27】121.买卖股票的最佳时机 122.买卖股票的最佳时机II
leetcode·golang
踢足球09291 小时前
寒假打卡:2026-2-8
数据结构·算法
IT猿手1 小时前
基于强化学习的多算子差分进化路径规划算法QSMODE的机器人路径规划问题研究,提供MATLAB代码
算法·matlab·机器人