英语链的接龙
接龙规则:
大家经常玩成语接龙游戏,我们试一试英语的接龙吧:一个文本文件中有N 个不同的英语单词, 我们能否写一个程序,快速找出最长的能首尾相连的英语单词链,每个单词最多只能用一次。
最长的定义是:最多单词数量,和单词中字母的数量无关。
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 | package file; import java.io.*; import java.util.*; public class ceshi { public static void main(String[] args)throws FileNotFoundException, IOException { File file= new File( "D:/《飘》英文版.txt" ); File file2= new File( "D:/output3707.txt" ); if (!file.exists()) { System. out .println( "文件不存在!" ); } else if (file.exists() && file.length() == 0) { System. out .println( "文件为空!" ); } //判断是否文件为空 else { BufferedReader br= new BufferedReader( new FileReader(file)); BufferedWriter bw = new BufferedWriter( new FileWriter(file2)) ; String s= "" ; int i,j; ArrayList<ArrayList<String>> listall= new ArrayList(); String key; String str; while ((str = br.readLine()) != null ) { s=s+str; } /* s=br.readLine();*/ String s2 = s.replaceAll( "\\s+" , " " ); System. out .println(s2); //将文本文件中的所有信息变为字符串 String []s1=s2.split( " " ); //以空格为分割划分每个单词 if (s1.length==1) System. out .println( "单词数为1" ); else { for (j=0;j<s1.length;j++) { ArrayList<String> list= new ArrayList<String>(); key=s1[j].substring(s1[j].length()-1); list.add(s1[j]); System. out .println( "key:" +key); for (i=1;i<s1.length;i++) { if (key. equals (s1[i].substring(0, 1))) { list.add(s1[i]); key=s1[i].substring(s1[i].length()-1); } else continue ; } listall.add(list); } int max=0; int count=0; for (i=0;i<listall.size();i++) { if (max<listall. get (i).size()) { max=listall. get (i).size(); count=i; } } for (i=0;i<listall. get (count).size();i++) { System. out .println(listall. get (count). get (i)); bw.write(listall. get (count). get (i)); bw.write( " " ); } br.close(); bw.close(); } } } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人