在给定字符串中查找字符串模式的重复 有人能回答下面的C++面试问题:
给定弦:“用印地语唱的歌” 查找重复的字符串,如下所示:在给定字符串中查找字符串模式的重复 有人能回答下面的C++面试问题:,c++,C++,给定弦:“用印地语唱的歌” 查找重复的字符串,如下所示: single characters repetition: “s”的计数=2“o”的计数=0“n”的计数=5“g”的计数=3 ..... 等 two character repetition Three character repetition “so”的计数=0“on”的计数=0“ng”的计数=3“in”的计数=4。。。。。等 two character repetition Three character repeti
single characters repetition:
“s”的计数=2“o”的计数=0“n”的计数=5“g”的计数=3
..... 等
two character repetition
Three character repetition
“so”的计数=0“on”的计数=0“ng”的计数=3“in”的计数=4。。。。。等
two character repetition
Three character repetition
“子”的计数=0….“ing”的计数=1。。。。等
Four character repetition
“歌曲”的计数=0…等
Rs这里有一个简单的方法
#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;
}
甚至递归函数也可以。要删除带有空白的“模式”,可以使用string::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;
}
#包括
#包括
#包括
类别FRQ{
void Func(std::map&frequencyTable,const std::string&m_str,const int stepping=1){
如果(步进==m_str.size()){
频率表[m_str]++;
返回;
}
对于(std::string::size_type i=0,iMAX=m_str.size();i 我们应该回答什么问题?“有人能回答下面的C++面试问题吗?”-是的,我们很多人都可以,但除非你自己努力解决这个问题,否则不太可能有人会。如果你不能自己解决这个问题,你就不是这个职位的合适人选。我会从std::map
或std::unordered_map
开始。有了这两种方法,任务应该很简单。@shaik786 W为什么“o”的计数等于0,而不是“o”的计数=1?如果我们必须在没有STL或任何内置API的情况下解决此问题,那么我们将如何解决此问题。如果此模式存在任何算法,是否有人可以告诉我。如果我们必须在没有STL或任何内置API的情况下解决此问题,那么我们将如何解决此问题。如果此模式存在任何算法,是否有人可以告诉我