Java for LeetCode 127 Word Ladder

來源:互聯網
上載者:User

標籤:

Given two words (beginWord and endWord), and a dictionary, 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 dictionary

For example,

Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]

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

解題思路一:

對set進行逐個遍曆,遞迴實現,JAVA實現如下:

static public int ladderLength(String beginWord, String endWord,Set<String> wordDict) {int result = wordDict.size() + 2;Set<String> set = new HashSet<String>(wordDict);if (oneStep(beginWord, endWord))return 2;for (String s : wordDict) {if (oneStep(beginWord, s)) {set.remove(s);int temp = ladderLength(s, endWord, set);if (temp != 0)result = Math.min(result, temp + 1);set.add(s);}}if (result == wordDict.size() + 2)return 0;return result;}public static boolean oneStep(String s1, String s2) {int res = 0;for (int i = 0; i < s1.length(); i++)if (s1.charAt(i) != s2.charAt(i))res++;return res == 1;}

 結果TLE

解題思路二:

 

Java for LeetCode 127 Word Ladder

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.