统计文本文件的最长子串的长度

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);
        }


    }

}

  总结:问题比较简单,主要是先从文件中读出字符串,然后将字符串存入HashMap之中,避免重复,然后依次比较第一个单词的最后一个和第二个单词的第一个,最后得出结果



posted @ 2023-03-05 18:33  樱花开到我身边  阅读(16)  评论(0)    收藏  举报