不准发言
- 积分
- 477
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2020-10-17
- 最后登录
- 1970-1-1
|
太多了
例如: word ladder
我记得2016,2018时的通解就是: 创建节点,替换a到z,
现在用那个通解,排名垫底
现在优化解法是加两个set
public int ladderLength(String beginWord, String endWord, List<String> set) {
Set<String> wordList = new HashSet<>(set);
if(!wordList.contains(endWord))
return 0;
Set<String> beginSet = new HashSet<>();
beginSet.add(beginWord);
Set<String> endSet = new HashSet<>();
endSet.add(endWord);
int res = 1;
while(!beginSet.isEmpty()){
Set<String> tempSet = new HashSet<>();
for(String word: beginSet){
char[] chs= word.toCharArray();
for(int i=0; i<chs.length; i++){
for(char c='a'; c<='z'; c++){
if(c==chs[i])
continue;
char old=chs[i];
chs[i]=c;
String newWord=String.valueOf(chs);
if(endSet.contains(newWord))
return res+1;
if(wordList.contains(newWord)){
tempSet.add(newWord);
wordList.remove(newWord);
}
chs[i]=old;
}
}
}
if(tempSet.size()<endSet.size() ){
beginSet=tempSet;
}else{
beginSet=endSet;
endSet=tempSet;
}
res++;
}
return 0;
}
|
|