Word Ladder

Word Ladder

问题:

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

思路:

  层次遍历

我的代码:

public class Solution {
    public int ladderLength(String start, String end, Set<String> dict) {
        if(isValid(start, end)) return 2;
        Set<String> rst = new HashSet<String>();
        for(String str : dict)
        {
            if(isValid(end,str))
            {
                rst.add(str);
            }
        }
        Queue<String> queue = new LinkedList<String>();
        queue.add(start);
        int level = 2;
        while(!queue.isEmpty())
        {
            int size = queue.size();
            for(int i = 0; i < size; i++)
            {
                String tmp = queue.poll();
                for(char c = 'a'; c <= 'z'; c++)
                {
                    for(int j = 0; j < tmp.length(); j++)
                    {
                        if(tmp.charAt(j) == c)  continue;
                        String str = replace(tmp, j, c);
                        if(rst.contains(str))  
                        {
                            return level + 1;
                        }
                        if(dict.contains(str))
                        {
                            queue.offer(str);
                            dict.remove(str);
                        }
                        
                    }
                }
            }
            level++;
        }
        return 0;
    }
    private String replace(String s, int index, char c)
    {
        char[] chars = s.toCharArray();
        chars[index] = c;
        return new String(chars);
    }
    public boolean isValid(String one, String two)
    {
        int count = 0;
        for(int i = 0; i < one.length(); i++)
        {
            if(one.charAt(i) != two.charAt(i))
                count++;
        }
        return count == 1 ? true : false;
    }
}
View Code
  • 层次遍历的应用之一,学习之处在于如何改变一个字符串的一位。

posted on 2015-03-22 20:39  zhouzhou0615  阅读(123)  评论(0编辑  收藏  举报

导航