01.题目及链接
题目链接:https://www.luogu.com.cn/problem/P1019
02.Debug执行流程案例
以下列数据为例
输入 #1**复制
5
at
touch
cheat
choose
tact
a
输出 #1复制
23
样例解释:连成的“龙”为 atoucheatactactouchoose
。
流程图说明:
at
(2)
表示at在“龙”尾时龙的长度为2
03.具体代码
public class P1019单词接龙 {
static String[] strs;//输入的字符串
static int len,n;
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
n=Integer.valueOf(in.readLine());
strs=new String[n+1];
int[] used=new int[n+1];
for (int i = 0; i <= n; i++) {
strs[i]=in.readLine();
}
dfs(' '+strs[n],1,used);
System.out.println(len);
}
private static void dfs(String strNow, int lengthNow,int[] used) {
len=Math.max(len, lengthNow);
for (int i = 0; i < n; i++) {
if(used[i]>=2) continue;
int coverLen=canLink(strNow,strs[i]);//获取重叠子串的长度
if(coverLen>0) {
used[i]++;
dfs(strs[i], lengthNow+strs[i].length()-coverLen,used);
used[i]--;
}
}
}
//获取重叠子串的长度
private static int canLink(String str1, String str2) {
int minLen=Math.min(str1.length(), str2.length());
for (int i = 1; i < minLen; i++) {
boolean flag=true;
for (int j = 0; j < i; j++) {
if(str2.charAt(j)!=str1.charAt(str1.length()-i+j)) flag=false;
}
if(flag) return i;
}
return 0;
}
}