zoukankan      html  css  js  c++  java
  • 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
    • 层次遍历的应用之一,学习之处在于如何改变一个字符串的一位。
  • 相关阅读:
    垂直的SeekBar:VerticalSeekBar
    android 获取路径目录方法以及判断目录是否存在,创建目录
    JSON
    列表和导航
    【前端积累】链接
    【前端积累】背景图像和背景替换
    【前段积累】可视化模型
    【前端积累】选择器
    银联支付-产品测试sdk使用流程
    【CSS系列】块级元素和行内元素
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4357938.html
Copyright © 2011-2022 走看看