给定字符串 S ,我想计算 n 次(1< = n< = s.length())时出现的子串数。我用滚动哈希完成了它,它可以通过使用后缀树来完成。如何使用复杂度为O(n ^ 2)的后缀数组来解决?
喜欢s =" ababaab"
n no.of string
4 1" a" (子串" a"存在4次)
3 2" b" ," ab" (子串" b"和" ab"有3次出现)
2 2" ba" ," aba"
1 14" aa" ," bab" ," baa" ," aab" ," abab" ....
答案 0 :(得分: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;
}