word ladder &word ladder 2

来源:互联网 发布:.net网络高级编程 pdf 编辑:程序博客网 时间:2024/05/20 18:23

word ladder
题意:给定start和end,一个字典序列,计算从start变成end,利用字典序列里的字符串进行转换,所需要变换次数。
例如,start = hit,end = cog ,dict = [“hot” , “dot” , “dog” , “lot” , “log”];
思路:使用BFS的遍历思路,对start,对其每一位上的字母从‘a’到‘z’进行替换,若是替换后的字符串和dict中的有相同,则选择这个相同的字符串,对其进行相同操作,并从dict中删除该字符串。
代码:

package com.WordLadder;import java.util.HashSet;import java.util.LinkedList;public class WordLadder {    public int ladderLength(String start , String end , HashSet<String>dict) {        LinkedList<String> wordQueue = new LinkedList<>();        int level = 1;        //记录当前层次上待处理字符串个数        int curnum = 1;        //记录下一层待处理的字符串个数        int nextnum = 0;        wordQueue.add(start);        while (!wordQueue.isEmpty()) {            String word =   wordQueue.poll();            curnum--;            for (int i = 0; i < word.length(); i++) {                char[] arr = word.toCharArray();                for(char j = 'a' ; j <= 'z' ; j++){                    arr[i] = j;                    String temp = new String(arr);                    if(temp.equals(end)){                        return level+1;                    }                    if(dict.contains(temp)){                        wordQueue.add(temp);                        nextnum++;                        dict.remove(temp);                    }                }            }            if(curnum == 0 ){                curnum = nextnum;                nextnum = 0;                level++;            }        }        return 0;    }    public static void main(String[] args) {        String start = "hit";        String end = "cog";        HashSet<String>dict = new HashSet<>();        dict.add("hot");        dict.add("dot");        dict.add("dog");        dict.add("lot");        dict.add("log");        System.out.println(new WordLadder().ladderLength(start, end, dict));        }    }}

word ladder 2
题意:此题搁置,暂时不会。
思路:
代码:

0 0
原创粉丝点击