這裏的計數是一個簡單的方法
#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;
}
如果你想與嵌入式空白排除patters你可以重寫程序通過以下方式
#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)
什麼問題是我們應該回答? – honk 2014-09-20 18:32:01
_「有人能回答下面的C++面試問題」 _ - 是的,我們很多人可以,但除非你把一些精力來解決這個問題你自己這是不可能的人的意願。如果你自己無法解決這個問題,那麼你不適合這個職位。 – 2014-09-20 18:41:17
我會用'的std :: map'或'的std :: unordered_map'開始。無論哪一種,這項任務都應該非常簡單。 – 2014-09-20 18:44:16