计算最长英语单词链

问题重述:大家经常玩成语接龙游戏,我们试一试英语的接龙吧:一个文本文件中有N 个不同的英语单词, 我们能否写一个程序,快速找出最长的能首尾相连的英语单词链,每个单词最多只能用一次。最长的定义是:最多单词数量,和单词中字母的数量无关。

程序需要考虑下列异常状况:例如,文件不存在,你的程序会崩溃么,还是能优雅地退出并给用户提示信息?如果文件没有任何单词、只有一个单词、没有可以首尾相连的单词,程序应该如何输出?如果输入文件有一万个单词,你的程序能多快输出结果?

设计思想:参考:https://www.cnblogs.com/CugYzc/p/9318531.html

首先将一个文本文件里面的单词读出来放入一个一维数组里面,方便操作。之后将单词的第一个字母和最后一个字母分别存入新创建的一维数组里面。而后通过循环进行判断便可以得到接龙单词链。

package com.java.fmd;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Scanner;

public class word {

    public static void main(String[] args) throws FileNotFoundException {
        File file = new File("input1.txt");// 读取文件
        if (!file.exists()) {// 如果文件打不开或不存在则提示错误
            System.out.println("文件不存在");
            return;
        }
        String[] strs=new String[1000];
        Scanner x = new Scanner(file);
        int i=0;
        while(x.hasNextLine()) {
            strs[i]=x.nextLine();
            i++;
        }
        String sentence = "";
        String word="";
        for(int m=0;m<i;m++) {
            sentence = strs[m];
            word = sentence;
            for(int j=m+1;j<i;j++) {
                if(strs[j].toLowerCase().subSequence(0, 1).equals(word.toLowerCase().subSequence(word.length()-1, word.length()))) {
                    word = strs[j];
                    sentence = sentence + "-" + word;
                }
            }
            if(sentence.indexOf("-")!=-1) {
                FileOutputStream bos = new FileOutputStream("output2.txt");
                System.setOut(new PrintStream(bos));
                System.out.println(sentence);
                break;
            }
        }
    }
}
原文地址:https://www.cnblogs.com/fuheishi/p/11056862.html