首页 文章

Boyer-moore计数词java

提问于
浏览
0

我在java中有一个作业,我必须使用Sedgewick的Boyer Moore子串搜索解决方案:http://algs4.cs.princeton.edu/53substring/BoyerMoore.java.html

现在它将在找到单词的第一个出现时停止并返回找到它的位置 . 所以为了计算单词,我将搜索方法更改为:

public String search(String txt) {
        int M = pat.length();
        int N = txt.length();
        int count = 0;
        int skip = 0;
        int charCount = 0;
        for (int i = 0; i <= N - M; i += skip) {
            skip = 0;
            for (int j = M-1; j >= 0; j--) {
                if (pat.charAt(j) != txt.charAt(i+j)) {
                    skip = Math.max(1, j - right[txt.charAt(i+j)]);
                    break;
                }
                charCount++;
            }
            if (skip == 0)
            {
                count++;
                skip++;
            }
        }
        return "Aantal char: " + charCount + "\n" + count;                      
    }

我更改了if skip语句以运行计数器“count”并在结束时返回它 . 会发生什么,如果我用手喂它一个模式和一些文本它似乎很好,所以:

模式:测试文本:“此测试是测试测试测试”结果:5

但是我需要读取一些大约70k字的文本的txt文件和子字符串搜索:

BufferedReader input = new BufferedReader(new FileReader(System.getProperty("user.home") + "/Desktop/opdr3tekst.txt"));
        StringBuilder stringBuilder = new StringBuilder();

        while(input.readLine() != null)
        {
            stringBuilder.append(input.readLine());
        }
        input.close();

        BoyerMoore boyer = new BoyerMoore("pattern to search");


        System.out.println(boyer.search(stringBuilder.toString()));

因此,当我搜索一个单词时,我总是会得到一个比我在Mac文本编辑器中CMD F文件本身少得多的数字 . 什么出了什么问题?

1 回答

  • 1

    在读取文件时,您正在跳过文件中的行 . 那是因为 while(input.readLine() != null) . 执行此语句时读取的行永远不会添加到 StringBuilder

    要解决这个问题,您可以执行以下操作:

    for(String line;(line = input.readLine())!=null;){
         stringBuilder.append(line);
    }
    

相关问题