LeetCode 127 Word Ladder

来源:互联网 发布:saber软件正版价格 编辑:程序博客网 时间:2024/05/17 02:04

Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:

  1. Only one letter can be changed at a time
  2. Each intermediate word must exist in the word list

For example,

Given:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]

As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.

Note:

  • Return 0 if there is no such transformation sequence.
  • All words have the same length.
  • All words contain only lowercase alphabetic characters.

Runtime: 21 ms beats 99.30% of java submissions.

public int ladderLength(String beginWord, String endWord, Set<String> wordList) {Set<String> start = new HashSet<>(), end = new HashSet<>();start.add(beginWord);end.add(endWord);return solve(start, end, wordList, 1);}public int solve(Set<String> start, Set<String> end, Set<String> wordList, int level) {if (start.isEmpty()) return 0;if (start.size() > end.size()) return solve(end, start, wordList, level);//cut the loopwordList.removeAll(start);wordList.removeAll(end);Set<String> set = new HashSet<>();for (String s : start) {char[] chars = s.toCharArray();for (int i = 0; i < s.length(); i++) {for (char ch = 'a'; ch <= 'z'; ch++) {char temp = chars[i];chars[i] = ch;String word = new String(chars);if (end.contains(word)) return level + 1;//found the word in other end(set)if (wordList.contains(word)) set.add(word);// if not, add to the next levelchars[i] = temp;}}}return solve(set, end, wordList, level + 1);}
https://discuss.leetcode.com/topic/40797/share-my-19ms-java-code
0 0
原创粉丝点击