Word Ladder (Java)

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.
每次变化一个的这种类型的题优先考虑有BFS,每次控制变化其中一个字母,然后和dict中的比较,如果一样就加到树的下一层。count值由层数决定。这道题相当于树的最小深度。
注意char和string的区别,尤其是equals方法和contains方法,编译器不会报错。前后如果一个是字符一个是字符串,即使字符串只含一个字符('b',"b"),也不会相等。
另注意:LinkedList是双链队列,add是加在队尾,push是加在队头,poll和pop都是删队头!
Source
public class Solution {
    public int ladderLength(String start, String end, Set<String> dict) {
        LinkedList<String> queue = new LinkedList<String>();
        queue.add(start);
        
        int count = 1;
        int cur = 1;
        int next = 0;
        
        while(!queue.isEmpty()){
        	String a = queue.poll();
        	if(dict.contains(a)){
        		dict.remove(a);  //dict里有start的先删除
        	}
        	cur --;
        	
        	
        	char[] str = a.toCharArray();
        	for(int i = 0; i < str.length; i++){
        		char temp = str[i];
        		for(char j = 'a'; j <= 'z'; j ++){
        			if(j == temp) continue;  //***
        			str[i] = j;
        			String b = new String(str); //注意不是toString 必须要先将str变为string才可以用下面的equals和contains判断
        			if(b.equals(end)) return ++count; //要写在判断contains之前       				
        			if(dict.contains(b)){   //contains
        					
        				queue.add(b);
        				next ++;
        				dict.remove(b);	//remove	
        					
        			}
        				
        		}
        		str[i] = temp; //变化完记得还原,这样可以保证每次遍历只变了其中一个字母
        		
        		
        	}
        	if(cur == 0){
        		cur = next;
        		next = 0;
        		count ++; //dict一层可能会有多个只变一个元素的  count应该在此处加而非dict.contains里面
        	}
        	
        }
        return 0;  
    }
}


Test
    public static void main(String[] args){
    	Set<String> dict = new HashSet<String>();
    	dict.add("hot");
    	dict.add("cog");
    	dict.add("dot");
    	dict.add("dog");
    	dict.add("hit");
    	dict.add("lot");
    	dict.add("log");
    	//dict.add("dot");
    	
    	System.out.println(new Solution().ladderLength("hit", "cog", dict));
    	//System.out.println(new Solution().ladderLength("a", "c", dict));
    
    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值