最大匹配字符串对 - 算法解析与代码实现
最大匹配字符串对 - 算法解析与代码实现
问题描述:
给你一个下标从 0 开始的数组 words,数组中包含互不相同的字符串。
如果字符串 words[i] 与字符串 words[j] 满足以下条件,我们称它们可以匹配:
- 字符串 words[i] 等于 words[j] 的反转字符串。
- 0 <= i < j < words.length
请你返回数组 words 中的 最大 匹配数目。
注意: 每个字符串最多匹配一次。
解题思路:
- 首先遍历数组 words,将每个字符串的反转字符串存储在一个新的数组 revWords 中。
- 再次遍历数组 words,对于每个字符串 words[i],在 revWords 中查找其反转字符串的位置。
- 如果找到了反转字符串的位置 j,且 j > i,则说明 words[i] 和 words[j] 可以匹配,将匹配数目加 1。
- 最后返回匹配数目即可。
代码实现:
def max_matching_pairs(words):
rev_words = [word[::-1] for word in words]
matching_count = 0
for i in range(len(words)):
for j in range(i + 1, len(words)):
if words[i] == rev_words[j]:
matching_count += 1
break
return matching_count
代码解释:
rev_words = [word[::-1] for word in words]:使用列表推导式快速生成 words 中每个字符串的反转字符串,并将它们存储在 rev_words 列表中。matching_count = 0:初始化匹配数目为 0。for i in range(len(words)):遍历 words 列表,外层循环用于遍历每个字符串。for j in range(i + 1, len(words)):内层循环用于遍历 words 列表中的剩余字符串,从 i+1 开始,避免重复匹配。if words[i] == rev_words[j]:判断当前字符串是否与 rev_words 中的某个字符串匹配。matching_count += 1: 如果匹配,则匹配数目加 1。break:如果找到匹配,则跳出内层循环,因为每个字符串最多匹配一次。return matching_count:返回最终的匹配数目。
示例:
words = ['abc', 'cba', 'xyx', 'zyx', 'yxz']
print(max_matching_pairs(words)) # 输出: 2
时间复杂度: O(n^2),其中 n 是 words 数组的长度。
空间复杂度: O(n),存储反转字符串需要额外的空间。
优化建议:
可以使用哈希表来优化时间复杂度,将反转字符串存储在哈希表中,查找时间复杂度可以降至 O(1)。
代码实现 (优化版本):
def max_matching_pairs_optimized(words):
rev_words = {}
for i, word in enumerate(words):
rev_words[word[::-1]] = i
matching_count = 0
for i in range(len(words)):
if words[i] in rev_words and rev_words[words[i]] > i:
matching_count += 1
return matching_count
代码解释:
rev_words = {}:使用字典存储反转字符串及其在 words 中的索引。for i, word in enumerate(words):遍历 words 列表,将每个字符串的反转字符串及其索引存储到字典中。if words[i] in rev_words and rev_words[words[i]] > i:判断当前字符串是否在字典中,并且其索引大于 i,保证不重复匹配。- 其他部分与之前版本相同。
优化后的时间复杂度: O(n),因为查找操作的时间复杂度降至 O(1)。
优化后的空间复杂度: O(n),仍然需要额外的空间存储反转字符串。
原文地址: http://www.cveoy.top/t/topic/oTeV 著作权归作者所有。请勿转载和采集!