Redian新闻
>
Time limit exceeded for Word Ladder(leetcode)
avatar
Time limit exceeded for Word Ladder(leetcode)# JobHunting - 待字闺中
x*0
1
按照leetcode的建议,用先变再查的方法来判断相邻的word。对大数据还是超时了。
下面是我的code,大家可不可以帮忙看看。
class Solution {
public:
int ladderLength(string start, string end, unordered_set &dict) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
unordered_set visited;
queue q;
q.push(start);
int curLevelLen = 1;
int nextLevelLen = 0;
int level = 1;

while (dict.size() > 0 && !q.empty()) {
string cur(q.front());
q.pop();
visited.insert(cur);

for (int i = 0; i < cur.size(); ++i) {

for (int j = 'a'; j <= 'z'; ++j) {
char copy = cur[i];
if (j == cur[i]) {
continue;
}

cur[i] = j;
if (cur == end) {
return level+1;
}

if (dict.find(cur) != dict.end() &&
visited.find(cur) == visited.end()) {
//if (dict.count(cur) > 0 && visited.count(cur) == 0)
q.push(cur);
++nextLevelLen;
}
cur[i] = copy;
}
}

--curLevelLen;
if (curLevelLen == 0) {
++level;
curLevelLen = nextLevelLen;
nextLevelLen = 0;
}
}

return 0;
}
};
相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。