單詞接龍的規則是可用於接龍的單詞 首字母必須要與前一個單詞的尾字母相同,當存在多個首字母相同的單詞時
取長度最長的單詞,如果長度也相等,則取字典序最小的單詞,已經參與接龍的單詞不能重復使用。
現給定一組全部由小寫字母組成的單詞數組,並指定其中一個單詞為起始單詞,進行單詞接龍
請輸出最長的單詞串,單詞串是單詞拼接而成的中間沒有空格
輸入描述
輸入第一行為一個非負整數,表示起始單詞在數組中的索引k 0<=k<N
輸入的第二行為非負整數N,接下來的N行分別表示單詞數組中的單詞
輸出描述,輸出一個字符串表示最終拼接的單詞串
示例
0
6
word
dd
da
dc
dword
d
輸出
worddwordda
說明 先確定起始單詞word 在接dword
剩余dd da dc 則取da
示例2
4
6
word
dd
da
dc
dword
d
輸出
dwordda
單詞個數1<N<20
單個單詞的長度 1~30
點擊查看代碼
import java.util.*;
public class Demo9 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
//接收輸入參數
int k = Integer.parseInt(sc.nextLine());
int N = Integer.parseInt(sc.nextLine());
ArrayList<String> list = new ArrayList<>();
for(int i = 0; i < N; i++){
list.add(sc.nextLine());
}
//確定好初始String以及tail
String temp = list.get(k);
list.remove(temp);
char tail = temp.charAt(temp.length() - 1) ;
//結果存儲在res中
ArrayList<String> res = new ArrayList<>();
res.add(temp);
while(getStr(list, tail) != null){
String str = getStr(list, tail);
res.add(str);
list.remove(str);
tail = str.charAt(str.length() - 1);
}
for(String s : res){
System.out.print(s);
}
}
//輔助函數,ArrayList是引用數據類型;將計算處理過程獨立出來,主函數只需寫邏輯過程
private static String getStr(ArrayList<String> list, char tail){
TreeSet<String> set = new TreeSet<>();
for(String s : list){
if(s.charAt(0) == tail){
set.add(s);
}
}
if(set.size() == 0){
return null;
}
String res = "";
int max = 0;
for(String s : set){
if(s.length() > max){
max = s.length();
res = s;
}
}
return res;
}
}
總結:要有良好的抽象能力,將整體和局部的關系拿捏好。
整體處理框架,寫邏輯過程;局部獨立出作為輔助函數,處理關鍵步驟的計算。