今天下午是一周一度的Java课,在课上,老师让我们做了一个小练习,但我还没有完全弄出来,下灭是我暂时的成果:
package aaa;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class aaa {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(new File("input.txt"));
HashSet<String> wordSet = new HashSet<String>();
List<String> wordList = new ArrayList<String>();
int maxLength = 0;
String longestChain = "";
// 将文件中的单词存入集合和列表中
while (scanner.hasNext()) {
String word = scanner.next().toLowerCase();
wordSet.add(word);
wordList.add(word);
}
scanner.close();
// 遍历列表,以每个单词作为起点查找最长的单词链
for (String word : wordList) {
HashSet<String> usedWords = new HashSet<String>();
String chain = word;
usedWords.add(word);
int length = findChain(wordSet, usedWords, chain);
if (length > maxLength) {
maxLength = length;
longestChain = chain;
}
}
// 将最长的单词链写入输出文件中
FileWriter writer = new FileWriter(new File("output.txt"));
writer.write(longestChain);
writer.close();
}
// 递归查找单词链
private static int findChain(HashSet<String> wordSet, HashSet<String> usedWords, String chain) {
int length = chain.split(" ").length;
String lastWord = chain.split(" ")[length - 1];
int maxLength = length;
for (String word : wordSet) {
if (!usedWords.contains(word) && word.charAt(0) == lastWord.charAt(lastWord.length() - 1)) {
HashSet<String> newUsedWords = new HashSet<String>(usedWords);
newUsedWords.add(word);
int newLength = findChain(wordSet, newUsedWords, chain + " " + word);
if (newLength > maxLength) {
maxLength = newLength;
}
}
}
return maxLength;
}
}
标签:总结,27,word,String,chain,HashSet,每日,length,new From: https://www.cnblogs.com/wass/p/17161923.html