繁体   English   中英

计算字符串的所有子字符串并检查给定条件的最快方法

[英]Fastest way to calculate all the substrings of a string and check it for a given condition

计算给定字符串的所有可能子字符串的最快方法是什么,并检查它们是否满足以下条件。

条件是:如果生成的子字符串的第一个和最后一个字符相同,则count增加1。 我们需要找到给定非常大的字符串的所有可能的子串。

我尝试过天真蛮力方法,但它不适用于长度为10 ^ 7的字符串。 请帮忙 :(

for(int c = 0 ; c < length ; c++ )
        {
            for( i = 3 ; i <= length - c ; i++ )
            {
                String sub = str.substring(c, c+i);
                System.out.println(sub);
                if(sub.charAt(0) == sub.charAt(sub.length()-1)){
                    count++;
                }
            }
        }

您当前的解决方案是输入字符串大小的二次方或O(n ^ 2)

您可以通过计算字符串中每个字符的出现次数,然后计算可以使用此字符创建的子字符串的数量来更有效地解决此问题。

例如,如果一个角色出现4次,那么这将导致3 + 2 + 1 = 6个子串。

您可以使用以下公式: ((n-1) * n) / 2

这会将算法的复杂性降低到O(n),因为对于每个字符的计数,您只需要遍历字符串一次。

我相信这段代码应该有效:

public static void main(String[] args) {
    String str = "xyzxyzxyzxyz";
    Map<Character, Integer> map = new HashMap<>();
    for (char c : str.toCharArray())
    {
        Integer count = map.get(c);
        if (count == null)
            count = 0;
        map.put(c, count + 1);
    }
    int sum = 0;
    for (int n : map.values())
        sum += ((n - 1) * n) / 2;
    System.out.println(sum);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM