[leetcode]Word Ladder

此题要多品品。由于是求最短的路径,所以用BFS,DFS会在大数据的时候超时,原因也容易理解。最终解法参考了:http://discuss.leetcode.com/questions/1108/word-ladder 和 http://blog.sina.com.cn/s/blog_b9285de20101j1xl.html

1.用了char[] curr=queue.poll().toCharArray();这个在字符串中间替换字符时很有用;
2.用了thisLevel和nextLevel。本来用DFS的时候记录dist很自然,多一个递归dist++就行了。BFS的时候有点不知所措,现在知道了可以记录这一层的个数和下一层的个数。

public class Solution {
    public int ladderLength(String start, String end, HashSet<String> dict) {
        int dist = 1;
        if (start.equals(end)) return dist;
        HashSet<String> added = new HashSet<String>();
        Queue<String> queue = new LinkedList<String>();
        queue.offer(start);
        added.add(start);
        int thisLevel = 1;
        int nextLevel = 0;
        while (queue.size() != 0)
        {
            char[] curr=queue.poll().toCharArray();
            thisLevel--;
            for (int i = 0; i < start.length(); i++)
            {
                char tmp = curr[i];
                for (char c = 'a'; c <= 'z'; c++)
                {
                    if (c == tmp) continue;
                    curr[i] = c;
                    String str = new String(curr);
                    if (str.equals(end)) return dist + 1;
                    if (dict.contains(str) && !added.contains(str))
                    {
                        queue.offer(str);
                        added.add(str);
                        nextLevel++;
                    }
                }
                curr[i] = tmp;
            }
            if (thisLevel == 0)
            {
                thisLevel = nextLevel;
                nextLevel = 0;
                dist++;
            }
        }
        return 0;
    }
}

其实说白了,就是topo图的BFS,建个图更清晰,但也更麻烦一些。

http://blog.csdn.net/beiyetengqing/article/details/8580577

posted @ 2013-08-31 21:43  阿牧遥  阅读(427)  评论(0)    收藏  举报