有人可以回答以下C ++面试问题:
鉴于字符串:"歌曲在印地文唱歌"
找到重复的字符串,如下所示:
single characters repetition:
" s" = 2" o" = 0" n" = 5" g" = 3 .....等等。
two character repetition
"所以" = 0" on" = 0" ng" = 3" in" = 4 .....等
Three character repetition
"儿子" = 0 ...." ing" = 1 ....等
Four character repetition
"歌曲" = 0 .....等
RS
答案 0 :(得分:0)
这是一种直截了当的方法
#include <iostream>
#include <string>
#include <map>
int main()
{
std::string s = "song singing in hindi";
for ( std::string::size_type i = 1; i <= s.size(); i++ )
{
std::map<std::string, size_t> m;
for ( std::string::size_type j = 0; j < s.size() - i + 1; j++ )
{
m[std::string( s, j, i )]++;
}
for ( const auto &p : m )
{
std::cout << "( \"" << p.first << "\", " << p.second << " ) ";
}
std::cout << std::endl;
}
return 0;
}
如果要排除带有嵌入式空白的模式,可以按以下方式重写程序
#include <iostream>
#include <string>
#include <map>
int main()
{
std::string s = "song singing in hindi";
for ( std::string::size_type i = 1; i <= s.size(); i++ )
{
std::map<std::string, size_t> m;
for ( std::string::size_type j = 0; j < s.size() - i + 1; j++ )
{
std::string t( s, j, i );
if ( t.find( ' ' ) == std::string::npos )
{
m[t]++;
}
}
if ( !m.empty() )
{
for ( const auto &p : m )
{
std::cout << "( \"" << p.first << "\", " << p.second << " ) ";
}
std::cout << std::endl;
}
}
return 0;
}
输出
( "d", 1 ) ( "g", 3 ) ( "h", 1 ) ( "i", 5 ) ( "n", 5 ) ( "o", 1 ) ( "s", 2 )
( "di", 1 ) ( "gi", 1 ) ( "hi", 1 ) ( "in", 4 ) ( "nd", 1 ) ( "ng", 3 ) ( "on", 1 ) ( "si", 1 ) ( "so", 1 )
( "gin", 1 ) ( "hin", 1 ) ( "ind", 1 ) ( "ing", 2 ) ( "ndi", 1 ) ( "ngi", 1 ) ( "ong", 1 ) ( "sin", 1 ) ( "son", 1 )
( "ging", 1 ) ( "hind", 1 ) ( "indi", 1 ) ( "ingi", 1 ) ( "ngin", 1 ) ( "sing", 1 ) ( "song", 1 )
( "hindi", 1 ) ( "ingin", 1 ) ( "nging", 1 ) ( "singi", 1 )
( "inging", 1 ) ( "singin", 1 )
( "singing", 1 )
答案 1 :(得分:0)
甚至递归函数都可以。删除&#39;模式&#39;使用空白区域,您可以使用字符串:: find函数来跟随Vlad的方法。
#include <iostream>
#include <string>
#include <map>
class FRQ {
void Func(std::map<std::string, size_t> &frequencyTable, const std::string &m_str, const int stepping = 1) {
if (stepping == m_str.size()) {
frequencyTable[m_str]++;
return;
}
for (std::string::size_type i = 0, iMAX = m_str.size(); i < iMAX; ++i) {
frequencyTable[m_str.substr(i, stepping)]++;
}
Func(frequencyTable, m_str, stepping + 1);
}
public:
std::map<std::string, size_t> *operator()(const std::string &str) {
std::map<std::string, size_t> *fTable = new std::map<std::string, size_t>();
Func(*fTable, str);
return fTable;
}
};
int main(void) {
using namespace std;
string s = "HiYo HiYo";
FRQ frq;
map<string, size_t> *frequenceTable = frq(s);
cout << "Patterns: " << frequenceTable->size() << endl;
for (const auto& ptr : *frequenceTable)
cout << "[ '" << ptr.first << "'::" << ptr.second << " ]" << endl;
delete frequenceTable;
return 0;
}