我的 word ladder ii

   

Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) 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"]

Return

[
    ["hit","hot","dot","dog","cog"],
    ["hit","hot","lot","log","cog"]
  ]

Note:

  • All words have the same length.
  • All words contain only lowercase alphabetic characters.
public List<List<String>> findLadders(String start, String end, Set<String> dict) {
        List<List<String>> rlt = new ArrayList<List<String>>();
        if(start.equals(end)){
            List<String> first = new ArrayList<String>();
            first.add(start);
            first.add(end);
            rlt.add(first);
            return rlt;
        }

        Queue<String> strs = new LinkedList<String>();
        Queue<Integer> lens = new LinkedList<Integer>();
        Queue<List<String>> lists = new LinkedList<List<String>>();
        int rltLen = dict.size() + 3;
        strs.add(start); lens.add(1); List<String> first = new ArrayList<String>(); first.add(start);
        lists.add(first);

        while(!strs.isEmpty()){
            String curStr = strs.poll();
            int index = lens.poll();
            List<String> list = lists.poll();
            System.out.println("index = "  + index + " list = " + list);
            if(index + 1 > rltLen){
                break;
            }

            for(int i = 0; i < curStr.length(); i ++){
                for(char change = 'a'; change <= 'z'; change ++){
                    if(change == curStr.charAt(i)){
                        continue;
                    }

                    String newStr = curStr.substring(0, i) + change + curStr.substring(i + 1);
                    if(newStr.equals(end)){
                        rltLen = index + 1;
                        List<String> clone = new ArrayList<String>(list);
                        clone.add(newStr);
                        rlt.add(clone);

                    } else if(dict.contains(newStr)){
                        List<String> clone = new ArrayList<String>(list);
                        clone.add(newStr);
                        lens.add(index + 1);
                        lists.add(clone);
                        strs.add(newStr);
                    }
                }
            }
        }
        return rlt;
    }


参照之前的 word ladder i 的答案。 我之前的法案构造多余的class 来连接每个str len list的关系,直到看到这样也可以。 可是总过不了oj.leetcode 说我memory limit exceed。 不知道怎么看。

  但是个人觉得这个解法比较简洁易懂。 在自己电脑上跑也ok




你可能感兴趣的:(我的 word ladder ii)