计算最长英语单词链
13 |
计算最长英语单词链 |
大家经常玩成语接龙游戏,我们试一试英语的接龙吧:一个文本文件中有N 个不同的英语单词, 我们能否写一个程序,快速找出最长的能首尾相连的英语单词链,每个单词最多只能用一次。最长的定义是:最多单词数量,和单词中字母的数量无关。 统一输入文件名称:input1.txt, input2.txt 统一输出文件名称:output1.txt,output2.txt 程序需要考虑下列异常状况: 例如,文件不存在,你的程序会崩溃么,还是能优雅地退出并给用户提示信息? 如果文件没有任何单词、只有一个单词、没有可以首尾相连的单词,程序应该如何输出? 如果输入文件有一万个单词,你的程序能多快输出结果?
|
要求将设计思想、代码实现、实现截图、个人总结以博文的形式发表。 |
(截止日期2019-6-9晚18:00) |
1 public class letter_follow_each_other_best { 2 3 public static void main(String[] args) throws FileNotFoundException { 4 File file = new File("D:\\emptys.txt");// 读取文件 5 if (!file.exists()) {// 如果文件打不开或不存在则提示错误 6 System.out.println("文件不存在"); 7 return; 8 }else { 9 if(file.exists() && file.length() == 0) { 10 System.out.println("文件为空!"); 11 return; 12 } 13 } 14 long startTime = System.currentTimeMillis(); 15 String[] strs=new String[1000000]; 16 Scanner x = new Scanner(file); 17 int i=0; 18 boolean flag=false; 19 while(x.hasNextLine()) { 20 String[] str=x.nextLine().split("\\W+"); 21 for(int ms=0;ms<str.length;ms++) { 22 if(!str[ms].equals("")&&str[ms].length()>2) { 23 flag=false; 24 // System.out.println(str[ms]); 25 if(i!=0) { 26 for(int t=0;t<i;t++) { 27 if(!str[ms].equals(strs[t])) { 28 flag=true; 29 } 30 } 31 }else { 32 flag=true; 33 } 34 35 if(flag) { 36 strs[i]=str[ms]; 37 i++; 38 } 39 40 } 41 42 } 43 } 44 if(i==1) { 45 System.out.println("该文件只有一个单词!无法实现词语接龙"); 46 } 47 String sentence = ""; 48 String word=""; 49 String max=""; 50 for(int m=0;m<i;m++) { 51 sentence = strs[m]; 52 word = sentence; 53 for(int j=m+1;j<i;j++) { 54 if(strs[j].toLowerCase().subSequence(0, 1).equals(word.toLowerCase().subSequence(word.length()-1, word.length()))) { 55 word = strs[j]; 56 sentence+="-"+word; 57 } 58 } 59 60 if(sentence.indexOf("-")!=-1) { 61 if(sentence.length()>max.length()) { 62 max = sentence; 63 } 64 // System.out.println(sentence); 65 } 66 67 } 68 long endTime = System.currentTimeMillis(); 69 System.out.println(endTime-startTime+"ms"); 70 System.out.println(i); 71 if(max.length()!=0) { 72 System.out.println(max); 73 }else { 74 System.out.println("没有首尾相连"); 75 } 76 77 } 78 }
因为代码的问题,有点儿不高兴,不想说啥,反正老师要求的功能都有的