【问题标题】:count number of occurence of each substring?计算每个子字符串的出现次数?
【发布时间】:2015-06-11 17:51:24
【问题描述】:

给定一个字符串 S,我想计算出现 n 次的子字符串的数量(1 滚动散列完成了,它可以通过使用后缀树来完成。如何使用复杂度 O(n^2) 的后缀数组来解决?

喜欢 s = "ababaab"

n 个字符串

4 1 "a" (子串 "a" 出现 4 次)

3 2 "b" , "ab" (子字符串 "b" 和 "ab" 出现 3 次)

2 2 "ba" , "aba"

1 14 "aa" , "bab" , "baa" , "aab" , "abab" ....

【问题讨论】:

  • 我建议您在问题中添加一个编程语言标签。这样你的问题更有可能得到回答。就目前而言,我不确定您使用的是哪种编程语言。
  • 我建议您添加一个示例这些字符串的外观,并简要说明如何处理这些字符串,因为我很难弄清楚您要完成什么。跨度>
  • 我建议你自己去,因为这不是一个“为我做”的网站!

标签: c++ string suffix-tree suffix-array


【解决方案1】:

这不是一个获取免费代码的论坛,但由于我今天晚上在这么好的模组中,我为你写了一个简短的例子。但我不能保证它没有错误,这是在 15 分钟内写的,没有特别的想法。

#include <iostream>
#include <cstdlib>
#include <map>

class CountStrings
{
    private:
            const std::string               text;
            std::map <std::string, int>     occurrences;

            void addString ( std::string );
            void findString ( std::string );

    public:
            CountStrings ( std::string );
            std::map <std::string, int> count ( );
};

void CountStrings::addString ( std::string text)
{
    std::map <std::string, int>::iterator iter;

    iter = ( this -> occurrences ).end ( );

    ( this -> occurrences ).insert ( iter, std::pair <std::string, int> ( text, 1 ));
}

void CountStrings::findString ( std::string text )
{
    std::map <std::string, int>::iterator iter;

    if (( iter = ( this -> occurrences ).find ( text )) != ( this -> occurrences ).end ( ))
    {
            iter -> second ++;
    }
    else
    {
            this -> addString ( text );
    }
}

CountStrings::CountStrings ( std::string _text ) : text ( _text ) { }

std::map <std::string, int> CountStrings::count ( )
{
    for ( size_t offset = 0x00; offset < (( this -> text ).length ( )); offset ++ )
    {
            for ( size_t length = 0x01; length < (( this -> text ).length ( ) - (  offset - 0x01 )); length ++ )
            {
                    std::string subtext;

                    subtext = ( this -> text ).substr ( offset, length );

                    this -> findString ( subtext );
            }
    }

    return ( this -> occurrences );
}

int main ( int argc, char **argv )
{
    std::string text = "ababaab";
    CountStrings cs ( text );
    std::map <std::string, int> result = cs.count ( );

    for ( std::map <std::string, int>::iterator iter = result.begin ( ); iter != result.end ( ); ++ iter )
    {
            std::cout << iter -> second << " " << iter -> first << std::endl;
    }

    return EXIT_SUCCESS;

}

【讨论】:

    猜你喜欢
    • 2022-10-15
    • 1970-01-01
    • 2016-01-23
    • 1970-01-01
    • 2020-02-21
    • 2012-02-12
    • 2020-07-23
    相关资源
    最近更新 更多