Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 02956a8

Browse files
Update Word Ladder
1 parent 4eeec1d commit 02956a8

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

‎精選高頻HARD題目/Word Ladder

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,3 +101,66 @@ public:
101101
return 0 ;
102102
}
103103
};
104+
105+
// 法二:因為此題 n > m,所以我們不使用找過所有字典的方法尋找合法字串,而是使用把所有可能的字串都嘗試過,出現在字典裡的我們就加入 queue 中
106+
107+
Time Complexity : O(mn) for O(n) nodes and each word will have O(26m) = O(m) valid words need to check
108+
Space Complexity : O(mn) for the hash map which store all the strings inside the wordList
109+
class Solution {
110+
public:
111+
bool valid(string &s1, string &s2) {
112+
int len = s1.length() ;
113+
int count = 0 ;
114+
for(int i = 0 ; i < len ; i++) {
115+
if ( s1[i] != s2[i] )
116+
count++ ;
117+
}
118+
return count == 1 ;
119+
}
120+
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
121+
queue<int> candidate ;
122+
123+
int target = -1 ;
124+
unordered_map<string, int> appear ;
125+
for( int i = 0 ; i < wordList.size() ; i++) {
126+
appear[wordList[i]] = i ;
127+
if ( valid(beginWord , wordList[i]) ) {
128+
candidate.push(i) ;
129+
}
130+
if ( endWord == wordList[i] )
131+
target = i ;
132+
}
133+
134+
if (target == -1)
135+
return 0 ;
136+
137+
int step = 2 ;
138+
int len = beginWord.length() ;
139+
while ( !candidate.empty() ) {
140+
int size = candidate.size() ;
141+
while ( size-- ) {
142+
int index = candidate.front() ;
143+
candidate.pop() ;
144+
if (index == target)
145+
return step ;
146+
147+
for(int i = 0 ; i < len ; i++) {
148+
char old = wordList[index][i] ;
149+
for(char c = 'a' ; c <= 'z' ; c++ ) {
150+
if (c == old)
151+
continue ;
152+
wordList[index][i] = c ;
153+
if ( appear.find(wordList[index]) != appear.end() ) {
154+
candidate.push( appear[wordList[index]] ) ;
155+
appear.erase( wordList[index] ) ;
156+
}
157+
}
158+
wordList[index][i] = old ;
159+
}
160+
}
161+
step++ ;
162+
}
163+
164+
return 0 ;
165+
}
166+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /