leetcode--Word Solitaire (Python)

Source: Internet
Author: User

Use dictionaries to reduce the complexity of lookups. Using list will time out.

1 classSolution:2 3     defnextwordslist (self, Word, worddict):4Res_list = []5          forIinchRange (len (word)):6              forJinchstring.ascii_lowercase:7New_word =list (word)8                 ifJ! =Word[i]:9New_word[i] =JTenNew_word ="'. Join (New_word) One                     ifNew_wordinchworddict: A res_list.append (New_word) -                         delWorddict[new_word] -         returnres_list the  -  -     defBFS (self, Beginword, Endword, worddict): -         #returns an int +Queue = [] -Queue.append ([Beginword, 1]) +          whileQueue: AWord, step = queue[0][0], queue[0][1] at queue.pop (0) -             ifWord = = Endword:returnStep -             #get the next time you change a word, get a list of words -Nextwords =self.nextwordslist (Word, worddict) -              forJinchnextwords: -Queue.append ([J, Step+1]) in         return0 -     defladderlength (self, Beginword, Endword, wordList): to         """ + : Type Beginword:str - : Type Endword:str the : Type WORDLIST:LIST[STR] * : Rtype:int $         """Panax Notoginseng         ifBeginwordinchWordList:wordList.remove (Beginword) -Worddict = {} the          forWinchWORDLIST:WORDDICT[W] = 1 +         returnSelf.bfs (Beginword, Endword, worddict)

leetcode--Word Solitaire (Python)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.