CSP-S/J信息学资料
时间限制: 1000 ms 内存限制: 65536 KB
提交数: 3149 通过数: 1750
【题目描述】
单词接龙是一个与我们经常玩的成语接龙相类似的游戏,现在我们已知一组单词,且给定一个开头的字母,要求出以这个字母开头的最长的“龙”(每个单词都最多在“龙”中出现两次),在两个单词相连时,其重合部分合为一部分,例如beast和astonish,如果接成一条龙则变为beastonish,另外相邻的两部分不能存在包含关系,例如at和atide间不能相连。
【输入】
输入的第一行为一个单独的整数n(n≤20)表示单词数,以下n行每行有一个单词(只含有大写或小写字母,长度不超过20),输入的最后一行为一个单个字符,表示“龙”开头的字母。你可以假定以此字母开头的“龙”一定存在。
【输出】
只需输出以此字母开头的最长的“龙”的长度。
【输入样例】
5
at
touch
cheat
choose
tact
a
【输出样例】
23
【来源】
No
代码如下:
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
Queue<String> queue = new LinkedList<String>();
int count = 1; // 记录树的深度
queue.offer(beginWord);
int currCount = 1;
int nextCount = 0;
while (!queue.isEmpty()){
count++;
for(int i = 0; i < currCount; i++){
String curr = queue.poll(); //获得队头元素
boolean flag = false;
for (int j = 0; j < wordList.size(); j++ ){
String one = wordList.get(j);
if(isOneLetterDiffer(curr, one)){
nextCount++;
if(one.equals(endWord)){
flag = true;
break;
}else{
queue.offer(one);
}
}
}
if(flag){
return count;
}
}
if(count > wordList.size() + 1) return 0;
currCount = nextCount;
nextCount = 0;
}
return count;
}
private boolean isOneLetterDiffer(String str1, String str2){
int i = 0, j = 0;
int count = 0;
while(i < str1.length() && j < str2.length()){
if(str1.charAt(i) != str2.charAt(j)){
count++;
}
if (count > 1)
return false;
i++;j++;
}
return true;
}