【问题标题】:Is this fact true about anagrammatical substrings?关于字谜子串,这个事实是真的吗?
【发布时间】:2016-08-10 00:39:08
【问题描述】:

我正在尝试编写一个算法来查找字符串的字谜子串的数量。例如,字符串"abba" 有 4:

(1)"a","a"

(2)"b","b"

(3)"ab","ba"

(4)"abb","bba"

我试图用来优化的一个事实是

如果一个字符串没有长度为 k 的子串的字谜对, 那么它没有长度为 k+1 的子串的字谜对

你能确认这是否属实吗?

因为我的算法

static int NumAnagrammaticalPairs(string str)
{
    int count = 0; // count of anagrammatical pairs found
    int n = str.Length / 2; // OPTIMIZATION: only need to look through the substrings of half the size or less
    for(int k = 1; k <= n; ++k) 
    {
        // get all substrings of length k
        var subsk = GetSubstrings(str,k).ToList();

        // count the number of anagrammatical pairs
        var indices = Enumerable.Range(0, subsk.Count);
        int anapairs = (from i in indices
                        from j in indices
                        where i < j && IsAnagrammaticalPair(subsk[i], subsk[j])
                        select 1).Count();

        // OPTIMIZATION: if didn't find any anagrammatical pairs in the substrings of length k, 
        // there are no anagrammatical pairs in the substrings of length k+1, so we can exit
        // the loop early
        if(anapairs == 0)
            break;
        else
            count += anapairs;
    }
    return count;       
}

正在得到结果sliggggtttthhhhly 偏离(通常偏离 1)测试用例中的实际结果。

【问题讨论】:

  • 你为什么在字符串的一半处停止?您的第 4 个示例(“abb”和“bba”)在长度为 4 的字符串中显示长度为 3 的对,当您的算法停止查看长度为 2 时。

标签: c# string algorithm optimization time-complexity


【解决方案1】:

情况并非如此 - abcdcdab 是长度为 4 的字谜,但您找不到长度为 3 的字谜子串。具体来说,abcdab 不起作用,因为它同时包含 abcdcdab,但没有 3 个字谜(来自 abcbcdcdadab)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-04
    • 2021-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-02
    • 2013-06-17
    • 2020-12-06
    相关资源
    最近更新 更多