首页 > 代码库 > My Solution: Word Ladder
My Solution: Word Ladder
public class Solution {
public int ladderLength(String start, String end, Set<String> dict) {
if (start == null || end == null || dict == null
|| start.length() != end.length()) {
return 0;
}
if (oneDiff(start, end)) {
return 2;
}
return helper(start, end, dict, 2);
}
public boolean oneDiff(String left, String right) {
int sameNumber = 0;
if (left == null || right == null) {
return false;
}
if (left.length() != right.length()) {
return false;
}
for (int i = 0; i < left.length(); i++) {
if (left.charAt(i) == right.charAt(i)) {
sameNumber++;
}
}
if (sameNumber == left.length() - 1) {
return true;
}
return false;
}
public int helper(String start, String end, Set<String> dict, int level) {
Queue<String> queue = new LinkedList<String>();
queue.offer(start);
HashMap<String,Integer> route = new HashMap<String,Integer>();
route.put(start,0);
while (!queue.isEmpty()) {
int qSize = queue.size();
for (int i = 0; i < qSize; i++) {
String cur = queue.poll();
for (int j = 0; j < cur.length(); j++) {
for (char c = 'a'; c <= 'z'; c++) {
if (cur.charAt(j) == c) {
continue;
}
StringBuffer sb = new StringBuffer(cur);
sb.setCharAt(j, c);
String nowStr = sb.toString();
if (nowStr.equals(end)) {
return level++;
}
if (dict.contains(nowStr)
&& !route.containsKey(nowStr)) {
queue.offer(nowStr);
route.put(nowStr,0);
}
}
}
}
level++;
}
return 0;
}
}
之后发现这个太丑了,用了算法导论上的方法,找一个东西来记录层数:
public class Solution { public int ladderLength(String start, String end, Set<String> dict) { if (start == null || end == null || dict == null || start.length() != end.length()) { return 0; } return helper(start, end, dict, 1); } public int helper(String start, String end, Set<String> dict, int level) { Queue<String> queue = new LinkedList<String>(); queue.offer(start); HashMap<String, Integer> route = new HashMap<String, Integer>(); route.put(start, 1); while (!queue.isEmpty()) { String cur = queue.poll(); int curLevel = route.get(cur); for (int j = 0; j < cur.length(); j++) { for (char c = 'a'; c <= 'z'; c++) { if (cur.charAt(j) == c) { continue; } StringBuffer sb = new StringBuffer(cur); sb.setCharAt(j, c); String nowStr = sb.toString(); if (nowStr.equals(end)) { return ++curLevel; } if (dict.contains(nowStr) && !route.containsKey(nowStr)) { queue.offer(nowStr); route.put(nowStr, curLevel + 1); } } } } return 0; } }
My Solution: Word Ladder
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。