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

题目描述:

给你一个下标从 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;
   }
};
相关推荐
wenyq719 小时前
LeetCode 2460. Apply Operations to an Array
算法·leetcode
.格子衫.20 小时前
032动态规划之区间DP——算法备赛
算法·动态规划
青 春 记 忆20 小时前
LeetCode 142. 环形链表 II|Python 解法详解
python·leetcode·链表
不会代码的小猴20 小时前
7. JSON
开发语言·c++·笔记·qt·算法·json
怪奇云呼军21 小时前
知识库也会注入指令?闪电智能VoiceAgent 如何防住 Prompt Injection
人工智能·python·算法·云计算·音视频
阿里云大数据AI技术1 天前
基于 EMR Serverless Ray 实现 Qwen 模型批量推理实践
人工智能·算法·agent
Rambo.xia1 天前
为什么去马赛克算法,决定了ISP的画质上限
算法·接口隔离原则
Benny_Tang1 天前
题解:P10230 [COCI 2023/2024 #4] Lepeze
c++·算法
Geek-Chow1 天前
06 训练管线:数据如何变成权重
人工智能·算法