题目描述
单词接龙是一个与我们经常玩的成语接龙相类似的游戏,现在我们已知一组单词,且给定一个开头的字母,要求出以这个字母开头的最长的“龙”(每个单词都最多在“龙”中出现两次),在两个单词相连时,其重合部分合为一部分,例如 beast和astonish,如果接成一条龙则变为beastonish,另外相邻的两部分不能存在包含关系,例如at 和 atide 间不能相连。
输入格式
输入的第一行为一个单独的整数n (n<=20)表示单词数,以下n 行每行有一个单词,输入的最后一行为一个单个字符,表示“龙”开头的字母。你可以假定以此字母开头的“龙”一定存在.
输出格式
只需输出以此字母开头的最长的“龙”的长度
样例输入
5
at
touch
cheat
choose
tact
a
输入
输入描述:
连成的“龙”为atoucheatactactouchoose
输入样例:
23
输出
输出描述:
输出样例:
HINT:时间限制:1.0s 内存限制:256.0MB
解题思路
用数组来接收单词,并找出长度最大的单词,并遍历数组来判断是否有可以接龙的单词,依次判断每个单词和其他单词的首尾能否重叠,这个注意要分龙头和不是龙头的部分。还有就是重复的单词不算。
代码
import java.util.Scanner;
public class Main {
public static int n;//几个字符串
public static int maxLength;//最长字符串的长度
public static String maxStr = "";//最长字符串
public static int[] count;
public static int first = 0;//第一次相连是肯定包含的
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
n = read.nextInt();
count = new int[n];
String[] ss = new String[n];
for (int i = 0; i < n; i++) {
ss[i] = read.next();
}
maxStr = read.next();
read.close();
dfs(maxStr, ss);
System.out.println(maxLength);
}
public static void dfs(String str, String[] ss) {
if (str.length() > maxLength) {
maxStr = str;
maxLength = str.length();
}
for (int i = 0; i < n; i++)//遍历一遍数组来看看有哪些可以接龙
{
if (count[i] < 2)//连接前提是这个字符串还要有次数
{
String str2 = ss[i];
int num = judgment(str, str2);
if (num != 0)//可以相连
{
count[i] = count[i] + 1;
String s = str + ss[i].substring(num);//这里可能出错!!!!!!!!!
dfs(s, ss);
count[i] = count[i] - 1;//回溯
}
}
}
}
//判断函数
public static int judgment(String str1, String str2) {
int len = 0;
if (str1.length() == 1)
{
for (int i = 0; i < Math.min(str1.length(), str2.length()); i++) {
String str11 = str1.substring(str1.length() - i - 1, str1.length());
String str22 = str2.substring(0, i + 1);
if (str11.equals(str22)) {
len = i + 1;
}
}
} else {
for (int i = 0; i < Math.min(str1.length() - 1, str2.length() - 1); i++) {
String str11 = str1.substring(str1.length() - i - 1, str1.length());
String str22 = str2.substring(0, i + 1);
if (str11.equals(str22)) {
len = i + 1;
break;
}
}
}
return len;
}
}


被折叠的 条评论
为什么被折叠?



