注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号
x
- class Node {
- public int level = 1;
- public Node previous;
- public String str;
- public Node(int l, Node n, String s) {
- level = l;
- previous = n;
- str = s;
- }
- }
- public class Solution {
- public List<List<String>> findLadders(String start, String end, Set<String> dict) {
- HashMap<String,HashSet<String>> neighbours = new HashMap<String,HashSet<String>>();
- dict.add(start);
- dict.add(end);
- for(String str : dict)
- buildGraph(neighbours, str, dict);
- List<List<String>> res = new ArrayList<List<String>>();
- LinkedList<Node> queue = new LinkedList<Node>();
- queue.add(new Node(1, null, start));
- int previousLevel = 0;
- HashMap<String,Integer> visited = new HashMap<String,Integer>();
- while(!queue.isEmpty()) {
- Node n = queue.poll();
- if(end.equals(n.str)) {
- if(previousLevel ==0 || n.level == previousLevel) {
- previousLevel = n.level;
- findPath(n, res);
- }
- else
- break;
- } else {
- HashSet<String> set = neighbours.get(n.str);
- if(set == null || set.isEmpty())
- continue;
- // ArrayList<String> toRemove = new ArrayList<String>();
- for(String s: set) {
- if(visited.containsKey(s)) {
- int occurLevel = visited.get(s);
- if(n.level+1 > occurLevel) {
- neighbours.get(s).remove(n.str);
- // toRemove.add(s);
- continue;
- }
- }
- visited.put(s, n.level + 1);
- queue.add(new Node(n.level + 1, n, s));
- if(neighbours.containsKey(s))
- neighbours.get(s).remove(n.str);
- }
- //for(String s: toRemove) {
- // set.remove(s);
- // }
- }
- }
- return res;
- }
- public void buildGraph(HashMap<String,HashSet<String>> neighbours, String str, Set<String> dict) {
- // int level = 1, next = 0, cur = 1;
- int len = str.length();
- char[] wordUnit = str.toCharArray();
- for(int i = 0; i < len; i++) {
- char c = wordUnit[i];
- for(char j = 'a'; j <='z'; j++) {
- if(c == j) //跑到和自身相同的字符串跳过去!
- continue;
- wordUnit[i] = j;
- String newstr = new String(wordUnit);
- if(dict.contains(newstr)) {
- HashSet<String> set = neighbours.get(str);
- if(set != null)
- set.add(newstr);
- else {
- HashSet<String> newset = new HashSet<String>();
- newset.add(newstr);
- neighbours.put(str,newset);
- }
- }
- }
- wordUnit[i] = c;
- }
- }
- public void findPath(Node n, List<List<String>> result) {
- ArrayList<String> path = new ArrayList<String>();
- Node p = n;
- while(p != null) {
- path.add(0, p.str);
- p = p.previous;
- }
- result.add(path);
- }
- }
复制代码 FindLadders中的if(previousLevel ==0 || n.level == previousLevel) {
previousLevel = n.level;
findPath(n, res);
}和if(n.level+1 > occurLevel) {
neighbours.get(s).remove(n.str);是在判断什么哦。。。谢谢了! |