This commit is contained in:
coderfengyun 2014-06-04 14:23:21 +08:00
parent 7010ea76ea
commit 9b01a16ccd
1 changed files with 81 additions and 0 deletions

View File

@ -0,0 +1,81 @@
package org.bench4q.agent.test;
import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;
import org.junit.Test;
public class Solution {
private static String LEVEL_END = "LEVEL_END";
public int ladderLength(String start, String end, Set<String> dict) {
int result = 1;
Set<String> footPrints = new HashSet<String>();
Queue<String> level = new LinkedList<String>();
level.offer(start);
level.offer(LEVEL_END);
while (!level.isEmpty()) {
result++;
String temp = level.poll();
if (temp.equals(LEVEL_END)) {
result++;
if (level.isEmpty()) {
continue;
}
level.offer(LEVEL_END);
continue;
}
for (String neighbor : getNeighbors(temp, dict)) {
if (!hasVisited(footPrints, neighbor)) {
footPrints.add(neighbor);
level.offer(neighbor);
if (neighbor.equals(end)) {
return result;
}
}
}
}
return 0;
}
private boolean hasVisited(Set<String> footPrints, String neighbor) {
return footPrints.contains(neighbor);
}
private Set<String> getNeighbors(String target, Set<String> dict) {
String temp = "";
Set<String> result = new HashSet<String>();
for (int i = 0; i < target.length(); i++) {
for (char c = 'a'; c < 'z'; c++) {
temp = buildNewStart(target, i, c);
if (temp.equals(target)) {
continue;
}
if (dict.contains(temp)) {
result.add(temp);
}
}
}
return result;
}
private String buildNewStart(String toBeChanged, int index, char replace) {
return toBeChanged.substring(0, index) + replace
+ toBeChanged.substring(index + 1);
}
@Test
public void test() {
Solution solution = new Solution();
assertEquals(
2,
solution.ladderLength("a", "c",
new HashSet<String>(Arrays.asList("a", "b", "c"))));
}
}