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

题目描述:

给你一个下标从 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;
   }
};
相关推荐
0 0 02 分钟前
CCF-CSP 33-2 相似度计算(jaccard)【C++】考点:STL容器(set/map)
开发语言·c++·算法
每天要多喝水5 分钟前
图论Day38:孤岛基础
算法·深度优先·图论
瓦特what?13 分钟前
波 浪 排 序
c++·算法·排序算法
blackicexs22 分钟前
第六周第日天
数据结构·算法
逆境不可逃23 分钟前
LeetCode 热题 100 之 48.旋转图像
算法·leetcode·职场和发展
Frostnova丶32 分钟前
LeetCode 1022. 从根到叶的二进制数之和
算法·leetcode
不会敲代码135 分钟前
别再背柯里化面试题了,看完这篇你自己也会写
javascript·算法·面试
snowfoootball37 分钟前
优先队列/堆 题目讲解
学习·算法
SamtecChina202338 分钟前
Samtec连接器设计研究 | 载流量:温升为什么重要?
大数据·网络·人工智能·算法·计算机外设
程序员南飞44 分钟前
排序算法举例
java·开发语言·数据结构·python·算法·排序算法