每日一题 2019 - 05 - 01
题目:
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:
- Only one letter can be changed at a time.
- Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
Note:
- Return 0 if there is no such transformation sequence.
- All words have the same length.
- All words contain only lowercase alphabetic characters.
- You may assume no duplicates in the word list.
- You may assume beginWord and endWord are non-empty and are not the same.
Example 1:
1 | Input: |
Example 2:
1 | Input: |
解法:
这个题给出开始与结束的两个长度相同的字符串,让找出从开始到结束包含在 wordlist
中的所有字符串组合,简单来说就是宽度优先搜索,从 beginword
开始进行搜索,对每一个待搜索单词进行挨个字符的递增变换,如果存在于 wordlist
中就加入到待查序列中,直到 wordlist
被查找完毕或者待查序列为空;
代码:
1 | class Solution { |