[LeetCode] Word Ladder string, leetcodeladder

Source: Internet
Author: User

[LeetCode] Word Ladder string, leetcodeladder

Title: Word Ladder

<Span style = "font-size: 18px;">/** LeetCode word ladder *: Given A Start word, an ending word, and a dictionary, you must change one character each time, become a new word in the dictionary until it becomes the final word and require its shortest path * idea: Use the queue to bring up the first word first, replace each character in a word until a word in the dictionary is found and added to the queue until the matching word is the last. * if such a path is not found, 0 */package javaTrain; import java. util. using list; import java. util. set; public class Train21 {public int ladderLength (String start, String end, Set <String> dict) {if (dict. size () = 0) return 0; queue list <String> queue = new queue list (); String tag = new String (); queue. add (start); queue. add (tag); int len = 1; while (queue. size ()> 1) {String top = queue. pop (); if (top = tag) {// indicates that the replacement test for each character of a word has been completed, and the useful ones are placed behind the queue by len ++; queue. add (tag); continue;} else if (top = end) {return len;} for (int I = 0; I <top. length (); I ++) {char [] zifu = top. toCharArray (); for (char c = 'a'; c <= 'Z'; c ++) {zifu [I] = c; string newWord = new String (zifu); if (dict. contains (newWord) {queue. add (newWord);} dict. remove (newWord) ;}}</span>
<span style="font-size:18px; font-family: Arial, Helvetica, sans-serif;"><span style="white-space:pre"></span>return 0;</span>

<span style="font-size:18px;">    }}</span>




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.