zoukankan      html  css  js  c++  java
  • Word Ladder

    注意各种数据结构的特点,删除的时候要注意遍历

     1 public class Solution {
     2     public int ladderLength(String start, String end, HashSet<String> dict) {
     3         // IMPORTANT: Please reset any member data you declared, as
     4         // the same Solution instance will be reused for each test case.
     5         
     6         LinkedList<String> queue = new LinkedList<String>();
     7         int count = 1;
     8         queue.add(start);
     9         
    10         while(!queue.isEmpty())
    11         {
    12             if(queue.contains(end))
    13                 return count;
    14             LinkedList<String> visited = new LinkedList<String>();
    15             while(!queue.isEmpty())
    16             {
    17                 String tmp = queue.poll();
    18                 for(int i=0;i < tmp.length(); i++)
    19                 {
    20                     for(char j = 'a'; j <= 'z'; j++)
    21                     {
    22                         char[] mychar = tmp.toCharArray();
    23                         mychar[i] = j;
    24                         if(dict.contains(String.valueOf(mychar)))
    25                         {
    26                             dict.remove(String.valueOf(mychar)); 
    27                             visited.add(String.valueOf(mychar));
    28                         }
    29                         
    30                     }
    31                 }
    32                 
    33             }
    34             queue.addAll(visited);
    35             count++;
    36         }
    37         return 0;
    38     }
    39     
    40     private boolean isladder(String str1, String str2)
    41     {
    42         if(str1.length() != str2.length())
    43             return false;
    44         int count = 0;
    45         for(int i=0; i<str1.length(); i++)
    46             if(str1.charAt(i) != str2.charAt(i))
    47                 count++;
    48         if(count == 1)
    49             return true;
    50         return false;
    51     }
    52 }
  • 相关阅读:
    javac 小记
    安全专家的工具箱
    MyBatis 缓存机制(十三)
    SpringMVC 环境搭建
    MyBatis 模糊查询的 4 种实现方式
    MyBatis 项目开发中是基于 XML 还是注解?
    MyBatis 动态 SQL 语句中出现 '<' 的问题
    数据库设计的三大范式
    mybatis 同时使用 XML 和注解
    数据库事务
  • 原文地址:https://www.cnblogs.com/jasonC/p/3417500.html
Copyright © 2011-2022 走看看