zoukankan      html  css  js  c++  java
  • leetcode--Word Ladder

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

    1. Only one letter can be 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 is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
    return its length 5.

    Note:

    • Return 0 if there is no such transformation sequence.
    • All words have the same length.
    • All words contain only lowercase alphabetic characters
    public class Solution {
       	/**
    	 * This is a typical bfs problem.
    	 * @param start
    	 * @param end
    	 * @param dict
    	 * @return
    	 */
        public int ladderLength(String start, String end, Set<String> dict) {
            if(dict.size() == 0) return 0;
            if(start.equals(end)) return 1;
    		
    		Queue<String> iteratedQueue = new LinkedList<String>();
    		Queue<Integer> depth = new LinkedList<Integer>();
    		
    		iteratedQueue.add(start);
    		depth.add(1);
    		
    		
    		while(iteratedQueue.peek() != null) {
    			String currentWord = iteratedQueue.poll();
    			int currentDepth = depth.poll();
    
    			for(int i = 0; i < currentWord.length(); ++i){
    				char[] carray = currentWord.toCharArray();
    				for(char c = 'a'; c <= 'z'; ++c){
    					carray[i] = c;
    					String possibleWord = new String(carray);
    					if(possibleWord.equals(end))
    					    return currentDepth + 1;
    					if(dict.contains(possibleWord)) {
    						iteratedQueue.add(possibleWord);
    						depth.add(currentDepth + 1);
    						dict.remove(possibleWord);
    					}
    				}
    			}
    		}
    		return 0;
        }
    }
    

      

  • 相关阅读:
    Java 基础
    Java 数据类型
    Spring 拦截器实现事物
    SSH 配置日记
    Hibernate 知识提高
    Jsp、Servlet
    leetcode 97. Interleaving String
    leetcode 750. Number Of Corner Rectangles
    leetcode 748. Shortest Completing Word
    leetcode 746. Min Cost Climbing Stairs
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3823614.html
Copyright © 2011-2022 走看看