【LetMeFly】2744.最大字符串配对数目:哈希表
力扣题目链接:https://leetcode.cn/problems/find-maximum-number-of-string-pairs/
给你一个下标从 0 开始的数组 words
,数组中包含 互不相同 的字符串。
如果字符串 words[i]
与字符串 words[j]
满足以下条件,我们称它们可以匹配:
- 字符串
words[i]
等于words[j]
的反转字符串。 0 <= i < j < words.length
请你返回数组 words
中的 最大 匹配数目。
注意,每个字符串最多匹配一次。
示例 1:
输入:words = ["cd","ac","dc","ca","zz"] 输出:2 解释:在此示例中,我们可以通过以下方式匹配 2 对字符串: - 我们将第 0 个字符串与第 2 个字符串匹配,因为 word[0] 的反转字符串是 "dc" 并且等于 words[2]。 - 我们将第 1 个字符串与第 3 个字符串匹配,因为 word[1] 的反转字符串是 "ca" 并且等于 words[3]。 可以证明最多匹配数目是 2 。
示例 2:
输入:words = ["ab","ba","cc"] 输出:1 解释:在此示例中,我们可以通过以下方式匹配 1 对字符串: - 我们将第 0 个字符串与第 1 个字符串匹配,因为 words[1] 的反转字符串 "ab" 与 words[0] 相等。 可以证明最多匹配数目是 1 。
示例 3:
输入:words = ["aa","ab"] 输出:0 解释:这个例子中,无法匹配任何字符串。
提示:
1 <= words.length <= 50
words[i].length == 2
words
包含的字符串互不相同。words[i]
只包含小写英文字母。
方法一:哈希表
使用哈希表统计每个单词的出现次数。遍历单词数组,假设当前单词是word,将word反转后的字符串在哈希表中出现的次数累加到答案中。之后,将这个单词在哈希表中出现的次数加一。
- 时间复杂度 O ( l e n ( w o r d s ) ) O(len(words)) O(len(words))
- 空间复杂度 O ( l e n ( w o r d s ) ) O(len(words)) O(len(words))
AC代码
C++
class Solution {
public:int maximumNumberOfStringPairs(vector<string>& words) {unordered_map<string, int> ma;int ans = 0;for (string& word : words) {ans += ma[string(1, word[1]) + word[0]];ma[word]++;}return ans;}
};
Python
from typing import List
from collections import defaultdictclass Solution:def maximumNumberOfStringPairs(self, words: List[str]) -> int:ma = defaultdict(int)ans = 0for word in words:ans += ma[word[1] + word[0]]ma[word] += 1return ans
后记
后记(是关于Github的)见下方”原文链接“。
同步发文于CSDN,原创不易,转载经作者同意后请附上原文链接哦~
Tisfy:https://letmefly.blog.csdn.net/article/details/135662583