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

题目描述:

给你一个下标从 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;
   }
};
相关推荐
wWYy.4 分钟前
数据结构:跳表
数据结构
txzrxz1 小时前
数论:排列数、组合数、费马小定理、逆元、同余定理
c++·算法·数论·组合数·费马小定理·逆元·排列数
xqqxqxxq1 小时前
LeetCode Hot100 双指针专项题解笔记
笔记·算法·leetcode
闪电悠米1 小时前
力扣hot100-54.螺旋矩阵-模拟边界控制详解
算法·leetcode·矩阵
变量未定义~1 小时前
虚拟节点-星石传送阵(4星)、强连通分量
数据结构·算法
IT方大同2 小时前
C语言分支与循环语句
c语言·开发语言·算法
待磨的钝刨2 小时前
深入理解主成分分析(PCA)
人工智能·线性代数·算法·机器学习
电子云与长程纠缠2 小时前
UE中使用TGuardValue与TInlineComponentArray数据结构
开发语言·数据结构·学习·ue5·游戏引擎
来一碗刘肉面3 小时前
串的定义与基本操作
数据结构
wWYy.3 小时前
算法:合并两个有序数组
数据结构·算法