首页 > 解决方案 > 查找给定字符串可能有多少个唯一子字符串

问题描述

我试图找出给定字符串可能有多少不同的子字符串。我想出了以下代码:

public static long process(String s) {
    long count = 0;
    for (int i = s.length() - 1; i > 0; i--) {
        Set<String> set = new HashSet<>();
        for (int j = 0; j < s.length() - i + 1; j++) {
            String a = s.substring(j, i + j);
            if (!set.contains(a))
                set.add(a);
        }
        count += set.size();
    }
    count++;
    return count;
}

我已经使用了这个代码:finding all distinct substring of a string。现在,当我将它用于大型输入时,我遇到了一些错误,例如某些输入,程序没有在时间限制内运行。

如何进一步改进此代码?

我什至尝试了后缀树方法,但同样的问题,它因超时错误而失败。

标签: javaalgorithm

解决方案


推荐阅读