【python/leetcode/127】Word Ladder

本文详细解析了LeetCode上单词阶梯(Word Ladder)问题的解决方案,采用Python实现,通过广度优先搜索(BFS)策略寻找从开始单词到目标单词的最短转换路径。代码中利用了集合和双端队列进行高效处理,最终实现在大部分提交中达到较快的运行速度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

https://leetcode.com/problems/word-ladder

实现代码

class Solution(object):
    def ladderLength(self, beginWord, endWord, wordList):
        """
        :type beginWord: str
        :type endWord: str
        :type wordList: List[str]
        :rtype: int
        """
        import collections
        
        if endWord not in wordList:
            return 0
        
        wordList = set(wordList)
        queue = collections.deque([[beginWord, 1]])
        while queue:
            word, length = queue.popleft()
            if word == endWord:
                return length
            for i in range(len(word)):
                for c in 'abcdefghijklmnopqrstuvwxyz':
                    next_word = word[:i] + c + word[i+1:]
                    if next_word in wordList:
                        wordList.remove(next_word)
                        queue.append([next_word, length + 1])
        return 0

总结

用python写这个题目,是比较tricky的,下次还是使用java写吧(等我熟悉以后),效率太低了,很容易就超时了

Runtime: 532 ms, faster than 49.55% of Python online submissions for Word Ladder.

这是我的效率,漫如龟

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值