diff --git a/Bench4Q-Agent/src/test/java/org/bench4q/agent/test/Solution.java b/Bench4Q-Agent/src/test/java/org/bench4q/agent/test/Solution.java new file mode 100644 index 00000000..5a57f891 --- /dev/null +++ b/Bench4Q-Agent/src/test/java/org/bench4q/agent/test/Solution.java @@ -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 dict) { + int result = 1; + Set footPrints = new HashSet(); + Queue level = new LinkedList(); + + 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 footPrints, String neighbor) { + return footPrints.contains(neighbor); + } + + private Set getNeighbors(String target, Set dict) { + String temp = ""; + Set result = new HashSet(); + 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(Arrays.asList("a", "b", "c")))); + } +}