最长英语单词链
大家經常玩成語接龍游戲,我們試一試英語的接龍吧:一個文本文件中有N 個不同的英語單詞, 我們能否寫一個程序,快速找出最長的能首尾相連的英語單詞鏈,每個單詞最多只能用一次。最長的定義是:最多單詞數量,和單詞中字母的數量無關。
統一輸入文件名稱:input1.txt,?input2.txt
統一輸出文件名稱:output1.txt,output2.txt
程序需要考慮下列異常狀況:
例如,文件不存在,你的程序會崩潰么,還是給用戶提示信息?
如果文件沒有任何單詞、只有一個單詞、沒有可以首尾相連的單詞,程序應該如何輸出?
如果輸入文件有一萬個單詞,你的程序會不會崩潰呢?
public class dancilian {public static void main(String[] args) {dancilian a=new dancilian(); File file = new File("E://test//input1.txt"); String b=a.read(file); String[] A =b.split(" ");String[] f; String[] l; String[] end; f=a.first(A); l=a.last(A); end=a.jielong(A, l, f);for(int i=0;i<3;i++) System.out.println(end[i]); try {a.write(end); } catch (Exception e) {e.printStackTrace(); }}public String[] first(String[] A){String[] F= new String[A.length];for(int i=0;i<A.length;i++){F[i]=A[i].substring(0,1);}return F;}public String[] last(String[] A){String[] L= new String[A.length];for(int i=0;i<A.length;i++){L[i]=A[i].substring(A[i].length()-1);}return L;} public String[] jielong(String[] A,String[] L,String[] F) {String[] end=new String[A.length];int k=0;end[0]=A[0];for(int j=0;j<A.length;j++){if((end[k].substring(end[k].length()-1)).equals(F[j])){end[++k]=A[j];}}return end;} public String read(File file){StringBuilder result = new StringBuilder();try{BufferedReader br = new BufferedReader(new FileReader(file));String s = null;while((s = br.readLine())!=null){result.append(System.lineSeparator()+s);}br.close(); }catch(Exception e){e.printStackTrace();}return result.toString(); } public void write(String[] str) throws Exception{File f = new File("E://test//output1.txt");OutputStream out = new FileOutputStream(f,true);for(int i=0; i<str.length; i++){out.write(str[i].getBytes()); out.write('\r'); out.write('\n'); }out.close(); System.out.println("寫入成功!");} }
轉載于:https://www.cnblogs.com/muailiulan/p/11070750.html
總結
- 上一篇: 学一下Linux
- 下一篇: Day2-Python基础2---列表、