每日总结 -计算最长单词链
一、题目内容:
大家经常玩成语接龙游戏,我们试一试英语的接龙吧:一个文本文件中有N 个不同的英语单词, 我们能否写一个程序,快速找出最长的能首尾相连的英语单词链,每个单词最多只能用一次。
最长的定义是:最多单词数量,和单词中字母的数量无关。
二、题目要求:
1、统一输入文件名称:input1.txt, input2.txt
2、统一输出文件名称:output1.txt,output2.txt
3、程序需要考虑下列异常状况:
(1)例如,文件不存在,你的程序会崩溃么,还是能优雅地退出并给用户提示信息?
(2)如果文件没有任何单词、只有一个单词、没有可以首尾相连的单词,程序应该如何输出?
(3)如果输入文件有一万个单词,你的程序能多快输出结果?
我们首先要导入文件
File file=new File("C://xunlei//test//input1.txt");
File file2=new File("C://xunlei//test//output.txt");
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis,"UTF-8");
我们可以将文本文件中的文字取出来,用java语句把它存成长字符串,然后再用split方法以特殊字符例如空格,逗号为间隔将长字符串分割成单词,存在字符串数组中。
代码如下:
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 82 83 84 85 86 87 88 89 90 91 92 93 94 | import com.sun.deploy.nativesandbox.NativeSandboxOutputStream; import java.io.*; import java.util.*; public class Letteron { public static void main(String[] args) throws FileNotFoundException, IOException { // TODO 自动生成的方法存根 File file= new File( "C://xunlei//test//input1.txt" ); File file2= new File( "C://xunlei//test//output.txt" ); if (!file.exists()) { System.out.println( "文件不存在!" ); } else if (file.exists() && file.length() == 0 ) { System.out.println( "文件为空!" ); } //判断是否文件为空 else { System.out.println( "文件存在" ); BufferedReader br= new BufferedReader( new FileReader(file)); BufferedWriter bw = new BufferedWriter( new FileWriter( "C://xunlei//test//output.txt" )) ; String s; int i,j; ArrayList<ArrayList<String>> listall= new ArrayList(); String key; s=br.readLine(); //将文本文件中的所有信息变为字符串 String []s1=s.split( " " ); //以空格为分割划分每个单词 if (s1.length== 1 ) System.out.println( "单词数为1" ); else { for (i= 0 ;i<s1.length;i++) { } //测试录入 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]); 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; } } System.out.println( "最长单词串为:" ); 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 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)