You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

技术求助:高效实现长度≥5的互为反转英文单词查找功能

Finding Length ≥5 Reverse Word Pairs Efficiently

Hey Kyle, let's figure out how to solve this reverse word pair problem efficiently—you're right that the sorted() approach for anagrams isn't the right fit here, since we're targeting strict reverse pairs (like "Damon" ↔ "nomad") rather than any rearranged-letter matches. Let's break down the solution step by step.

Key Difference to Clarify

First, let's separate two similar but distinct concepts:

  • Palindromes: Words that are the same forwards and backwards (e.g., "level"). We want to exclude these since we're looking for pairs of different words.
  • Reverse pairs: Two distinct words where one is exactly the reverse of the other (e.g., "Damon" reversed is "nomad"). These aren't just anagrams—they have a strict order reversal.

Efficient Approach Using Hash Tables

The most efficient way to tackle this is to use a hash-based structure (like a Python dictionary or set) to track words we've already processed. This lets us check for the existence of a reversed word in average O(1) time, leading to an overall time complexity of O(n*k) where:

  • n = number of words
  • k = average length of the words (from reversing each word)

Solution Code (Preserves Original Case)

This version keeps the original word casing while handling case insensitivity for matching (so "Damon" and "nomad" are recognized as a pair):

def find_reverse_word_pairs(words):
    reverse_map = {}  # Key: lowercase reversed word, Value: list of original words
    unique_pairs = set()

    for word in words:
        # Skip words shorter than 5 characters
        if len(word) < 5:
            continue
        
        lower_word = word.lower()
        reversed_lower = lower_word[::-1]

        # Check if current word is the reverse of any already processed word
        if lower_word in reverse_map:
            for partner in reverse_map[lower_word]:
                # Skip palindromes (word is identical to its reverse)
                if lower_word != reversed_lower:
                    # Sort the pair to avoid duplicates (e.g., ("Damon", "nomad") vs ("nomad", "Damon"))
                    sorted_pair = tuple(sorted((word, partner)))
                    unique_pairs.add(sorted_pair)
        
        # Add current word to the map, using its reversed lowercase as the key
        if reversed_lower not in reverse_map:
            reverse_map[reversed_lower] = []
        reverse_map[reversed_lower].append(word)

    return list(unique_pairs)

Simplified Version (Lowercase Only)

If you don't need to preserve original casing, this set-based version is even leaner:

def find_reverse_word_pairs_lower(words):
    seen_words = set()
    unique_pairs = set()

    processed_words = [word.lower() for word in words if len(word) >= 5]

    for word in processed_words:
        reversed_word = word[::-1]
        if reversed_word in seen_words:
            # Skip palindromes
            if word != reversed_word:
                unique_pairs.add(tuple(sorted((word, reversed_word))))
        seen_words.add(word)

    return list(unique_pairs)

Why This Works Better Than sorted()

Using sorted(word) would group all anagrams together, which includes way more pairs than just reverse matches. For example, "listen" and "silent" are anagrams but not reverses. This approach targets exact reverses directly, avoiding irrelevant matches and keeping the logic focused.

Performance Notes

  • The hash table lookups are average O(1), so this scales well even with large word lists (like dictionaries with tens of thousands of entries).
  • We use a set for unique_pairs to automatically handle duplicate pairings (e.g., when we process "nomad" after "Damon", we don't add the same pair twice).

内容的提问来源于stack exchange,提问作者KyleMcCann

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:51:19