127. Word Ladder

Source: Internet
Author: User

    /** 127. Word Ladder * 2016-5-21 by Mingyang * This is a typical topic to convert the topic to graph, first we start with a string start * We first map the topic, vertex is each string, then     The last two strings, if one character apart, we make a connection. * Next look at the advantages of this method, notice that our character set has only lowercase letters, and the string length is fixed, * assumed to be L. Then you can notice that each character can correspond to the edge of 25 (26 lowercase letters minus themselves), * then a string may exist edge is 25*l bar.     The next step is to detect if the strings of these edges are in the dictionary and get a complete picture structure.     * Key 1. Just as we used to do with the queue when we used to do the tree, so that all the child nodes are push into the queue, and each line is accurate to how many of the number of the bank * Good control when to enter the next line. */     Public intLadderlength (string start, String end, set<string>dict) {        if(Start = =NULL|| End = =NULL|| Start.length () = = 0 | | End.length () = = 0 | | Start.length ()! =end.length ())return0; LinkedList<String> queue =NewLinkedlist<string>(); Set<String> visited =NewHashset<string>(); intLevel = 1; intLastnum = 1; intCurnum = 0;        Queue.offer (start);        Visited.add (start);  while(!Queue.isempty ()) {String cur=Queue.poll (); Lastnum--;  for(inti = 0; I < cur.length (); i++) {                Char[] Charcur =Cur.tochararray ();  for(Charc = ' a '; C <= ' z '; C++) {Charcur[i]=C; String Temp=NewString (charcur); if(Temp.equals (end))returnLevel + 1; if(Dict.contains (temp) &&!visited.contains (temp)) {Curnum++;                        Queue.offer (temp);                    Visited.add (temp); }                }            }            if(Lastnum = = 0) {Lastnum=Curnum; Curnum= 0; level++; }        }        return0; }

127. Word Ladder

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.