新农上路
- 积分
- 96
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2016-10-16
- 最后登录
- 1970-1-1
|
- public class WordLadderIII {
- public static void main(String[] args) {
- WordLadderIII w = new WordLadderIII();
- Set<String> dict = new HashSet<>();
- dict.add("hot");
- dict.add("dot");
- dict.add("dog");
- dict.add("lot");
- dict.add("log");
- dict.add("cog");
- List<List<String>> res = w.getAllLadders("hit", "cog", dict);
- for (List<String> list : res) {
- for (String s : list) {
- System.out.print(s + "->");
- }
- System.out.println();
- }
- }
- public List<List<String>> getAllLadders(String start, String end, Set<String> dict) {
- List<List<String>> res = new ArrayList<>();
- if (dict == null || dict.size() == 0) {
- return res;
- }
- dict.remove(start);
- List<String> list = new ArrayList<>();
- list.add(start);
- helper(res, start, end, dict, list);
- return res;
- }
- public void helper(List<List<String>> res, String start, String end, Set<String> set, List<String> list) {
- if (start.equals(end)) {
- res.add(new ArrayList<>(list));
- return;
- }
- for (int i = 0; i < start.length(); i++) {
- StringBuilder sb = new StringBuilder(start);
- for (char c = 'a'; c <= 'z'; c++) {
- sb.setCharAt(i, c);
- String newStr = sb.toString();
- if (set.contains(newStr)) {
- set.remove(newStr);
- list.add(newStr);
- helper(res, newStr, end, set, list);
- list.remove(list.size() - 1);
- set.add(newStr);
- }
- }
- }
- }
- }
复制代码 |
|