yetang307

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

public class test_a {

    public static void main(String[] args) throws IOException {

        String path = "F:/piao.txt";

        FileInputStream fis = new FileInputStream(path);

        InputStreamReader inputStreamReader = new InputStreamReader(fis, "GBK");

        char[] chars = new char[1024];

        String content= "";

        while (inputStreamReader.read(chars) > 0 ) {

            content += new String( chars );

        }

        int addyuansu=0;

        //2.依次取出首位字母存入数组中

        String[] newwords=new String[100000];//去重后的单词数组

        String[] wordschain=new String[100000];

        int wordschainindex=0;

        int[] wordsmaxlen=new int[100000];

        String[] words = content.split("[^(a-zA-Z)]+");

        Set<String> set  =new HashSet<String>();

        for(int i=0;i<words.length;i++)

        {

            //System.out.println(words[i]);

            if (!words[i].equals("")&&words[i].length()>0&&words[i]!=null)

            {

                boolean add = set.add(words[i]);

                if(add){

                    newwords[addyuansu++]=words[i];

                }

            }

        }

       //3.依次比较第一个单词和第二个单词的字母

        for(int i=0;newwords[i]!=null;i++)

        {

            wordschain[wordschainindex++]=newwords[i];

            String s1 = wordschain[wordschainindex - 1];

            int count=0;

            for(int j=i+1;newwords[j]!=null;j++){

                if(s1.charAt(s1.length()-1)==newwords[j].charAt(0))

                {

                    s1=s1+" ";

                    s1+=newwords[j];

                    count++;

                }

            }

            wordsmaxlen[wordschainindex-1]=count;

            wordschain[wordschainindex-1]=s1;

        }

        int maxlen=0;

        for(int k=0;k<wordschainindex-1;k++)

        {

            if(wordsmaxlen[k]>=maxlen)

            {

                maxlen=wordsmaxlen[k];

            }

        }

        String[] strings = wordschain[maxlen].split(" ");

        System.out.println("最长子链是");

        for (String s:strings)

        {

            System.out.println(s);

        }

    }

}

posted on 2023-03-30 12:58  椰糖  阅读(20)  评论(0)    收藏  举报