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

题目描述:

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

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

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

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

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

解法一:枚举

二重循环,枚举给定的数组 words 中的 wordsi 和 wordsj是否可以匹配

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 分钟前
接下来我将复现 10 篇强化学习算法:第 3 篇,一杯喜茶,搞定 Search-R1
算法·面试
geovindu1 小时前
CSharp: Recursion Algorithm
开发语言·后端·算法·c#·递归算法
z小猫不吃鱼1 小时前
ResRep: Lossless CNN Pruning via Decoupling Remembering and Forgetting
算法·cnn·剪枝
卡提西亚1 小时前
leetcode-239. 滑动窗口最大值
算法·leetcode·职场和发展
ShallWeL1 小时前
【机器学习】(20)—— 类别不平衡
人工智能·算法·机器学习
明志数科1 小时前
具身智能数据标准化:从碎片化接口到统一工作组的技术路径
人工智能·算法·机器学习
旖-旎2 小时前
LeetCode 494:目标和(动态规划/01背包问题)—— 题解
c++·算法·leetcode·动态规划·01背包
spssau2 小时前
一文学会结构方程模型:从模型搭建、路径图绘制到不达标调整,实操全流程
人工智能·python·算法
zzz_23682 小时前
【Java实习面试算法冲刺】总复盘
java·算法·面试
DFT计算杂谈2 小时前
DeepSeek 集群服务器无root本地部署指南
数据库·人工智能·python·opencv·算法