计算每个子字符串的出现次数
count number of occurence of each substring?
给定一个字符串 S,我想计算出现 n 次的子字符串的数量(1 <= n <= s.length())。我已经用滚动哈希完成了它,它可以通过使用后缀树来完成。如何使用复杂度 O(n^2) 的后缀数组求解?
就像 s = "ababaab"
一样n 个字符串编号
41 "a"(子字符串"a"出现 4 次)
3 2 "b", "ab"(子字符串"b"和"ab"出现3次)
22 "ba" , "aba"
1 14 "aa" , "bab" , "baa" , "aab" , "abab" ....
这不是一个获取免费代码的论坛,但由于我在这个 evning 中处于如此良好的状态,我为您写了一个简短的示例。但我不能保证没有错误,这是在 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;
}
相关文章:
- 我的目标是编写一个程序来计算和存储字符串在字符数组中出现的位置
- 通过字符串来计算长度需要更长的时间,而不是移动字符串几次?
- 如何计算特定字母在字符串中出现的次数?(C++)
- 计算在同一位置至少包含一个常用字符的不同字符串对
- 给定一个单词数组和一个字符串,如何计算给定字符串中的所有单词
- 使用标准库计算字符串中的十进制数
- 如何计算字符串中用户输入元素的出现次数?
- 如何在 C++ 中计算字符串的算术运算
- 计算字符串中子字符串的出现次数
- 用于计算字符串中元音的函数
- 当 NUL 字符被定义为字符串的一部分时,为什么 strlen() 不计算终止 NUL 字符的字节?
- 计算表达式字符串由 std::map 中的键组成
- 如何计算字符串 c++ 中的"xxx"数?
- 通过将文本文件读取为字符串/向量来计算加权/未加权 GPA
- 如何更有效地计算n个字符串之间的不匹配分数?
- 将字符串计算为 C++ 中的表达式
- 在C++中从字符串计算算术表达式
- 在字符串计算后添加空字符
- C++使用C字符串计算文件中的字符、单词、句子
- 不使用字符串计算数字中的数字