zoukankan      html  css  js  c++  java
  • 127. Word Ladder via java

    A classic BFS problem, that is, we use a Queue to store temporary solution and record the size of the current Queue. 

    For each node in this BFS tree, we try k times of transformation, k is the length of the word.

    We record every word which already has been seen in case of a loop. Thus we need a HashSet.

    public class Solution {
      // use BFS to solve
      // in every level of BFS searching, 
      // we find the word that replaced by one char and also in the dict without have seen before
      // data structure: seen(HashSet), cur(Queue)
      // assume that the wordList is not null, case insensitive, no duplicate, every word is non-empty
      public int ladderLength(String beginWord, String endWord, List<String> wordList) {
        // Write your solution here
        HashSet<String> seen = new HashSet<>();
        Queue<String> cur = new LinkedList<>();
        seen.add(beginWord);
        cur.offer(beginWord);
        int cnt = 1;
        while(cur.size()>0){
          cnt++;
          int size = cur.size();
          for(int i=0; i<size; i++){
            String todo = cur.poll();
            for(int j=0; j<todo.length(); j++){
              List<String> changed= getQualified(todo, j, wordList, seen);
              for(String s: changed){
                if(String.valueOf(s)==String.valueOf(endWord)){
                  return cnt;
                }else{
                  cur.offer(s);
                  seen.add(s);
                }
              }
            }
          }
        }
        return 0;
      }
    
      private List<String> getQualified(String from, int ignore, List<String> wordList, HashSet<String> seen){
        List<String> res = new ArrayList<>();
        for(String s: wordList){
          int flag = 0;
          for(int i=0; i<from.length(); i++){
            if(i!=ignore && from.charAt(i)!=s.charAt(i)){
              flag=1;
            }
          }
          if(flag==0 && !seen.contains(s)){
            res.add(s);
          }
        }
        return res;
      }
    }
  • 相关阅读:
    查看资源加载各环节具体耗时的利器
    WebStorm 格式化代码快捷键
    Android 如何使edittext默认失去焦点
    html语义化练习易牛课堂代码
    html网页练习豆瓣网
    HTML前期学习总结
    视频课阶段基础知识总结
    MQ、JMS 关系的理解
    Jvm参数配置
    Java泛型
  • 原文地址:https://www.cnblogs.com/zg1005/p/11980615.html
Copyright © 2011-2022 走看看