[Leetcode] [JAVA] Word Ladder

Source: Internet
Author: User

Given words (start and end), and a dictionary, find the length of shortest transformation sequence F Rom start to end, such that:

    1. One letter can is changed at a time
    2. Each intermediate word must exist in the dictionary

For example,

Given:
Start ="hit"
End ="cog"
dict =["hot","dot","dog","lot","log"]

As one shortest transformation "hit" -> "hot" -> "dot" -> "dog" -> "cog" is,
return its length 5 .

Note:

      • Return 0 If there is no such transformation sequence.
      • All words has the same length.
      • All words contain only lowercase alphabetic characters.

At first glance it is difficult to find a problem, in fact, careful analysis is the graph traversal. Think of the words in both start,end and dict as a knot, and if one word can legitimately be converted to another, then there is a path between the two "nodes". The problem is changed to find the shortest path length from start to end.

If you are using a method that scans all dict words and then determines whether they are legitimate to traverse the node, it will time out (because there are cases with too many words in the dict). So you can only use other traversal ideas.

An efficient way to traverse is to get to the current word length, and then to each bit to try to replace it with another character to Traverse, that is, to get the possible legal string, and then determine whether it is equal to end, or in dict and not in the traversed node, so that the time complexity is O (l) only with the length of the word.

For each node, the HashMap is used to save the start to its path length, and the new node will only need to add a length when entering the site.

It is better to use breadth-first traversal, because we only need to get the shortest path length, and breadth first ensures that the first path to end is the shortest (that is, you can return when you reach end).

The code is as follows:

1      Public intLadderlength (string start, String end, set<string>dict) {2Hashmap<string, integer> HM =NewHashmap<string, integer>();3queue<string> q =NewLinkedlist<string>();4 Q.add (start);5Hm.put (start,1);6         7          while(!q.isempty ())8         {9String temp =Q.poll ();Ten             intLen =Hm.get (temp); One              for(intI=0;i<temp.length (); i++) { A                  for(CharC= ' a '; c<= ' z '; C + +) { -                     if(c==Temp.charat (i)) -                         Continue; theStringBuilder SB =NewStringBuilder (temp); - Sb.setcharat (i,c); -String next =sb.tostring (); -                      +                     if(Next.equals (end)) -                         returnLen+1; +                     if(Dict.contains (next) &&!Hm.containskey (Next)) { A Q.add (next); atHm.put (next,len+1); -                     } -                 } -             } -         } -         return0; in}

[Leetcode][java] Word Ladder

Related Article

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.