#include<iostream>
using namespace std;
void check_exist_get_count(string str,char ch)
{
int counter=0;
for(int x=0;x<str.length();x )
{
if(str[x]==ch)
counter ;
}
cout<<ch<<" : "<<counter;
}
int main ()
{
string str;
cin>>str;
for(int x=0;x<str.length();x )
{
check_exist_get_count(str,str[x]);
}
return 0;
}
如果沒有內置函式,我需要計算字母的出現次數,但我有問題,我應該使用什么條件來檢查哪個 make for 回圈不會多次發送字母示例:在我的代碼中,我得到輸入 aaabbc 輸出
a:3a:3a:3b:2b:2c:1
但要求的答案應該是
a:3 b:2 c:1
uj5u.com熱心網友回復:
您只是在主函式中迭代字串一次,對于該字串中的每個字符,再次遍歷整個字串并計算其中有多少個這樣的字符。
您不做的是跟蹤您已經計算過哪些字符,這就是為什么要多次計算它們的原因。不要嵌套回圈(在第一個回圈內呼叫您的函式),而是將這些東西分開:
一種選擇是對字串進行第一次傳遞,您只需構建一個字串中的字串列,如下所示:
std::set<char> chars;
for (char c: str)
{
chars.insert(c); // a set doesn't allow duplicate entries
// so you don't have to check yourself if it's already in there
}
然后,您可以在第二個回圈中為集合中的每個字符呼叫 count。但是,這仍然是低效的;到目前為止,您可以使用地圖來跟蹤哪些字符以及它們的數量。像這樣的東西:
計算字符頻率直方圖的代碼可能如下所示:
#include <iostream>
#include <map>
#include <string>
int main ()
{
std::string str("aaabbc");
std::map<char, size_t> charHistogram;
for (char c: str)
{
// if c not contained in map yet, it's automatically initialized to 0
charHistogram[c];
}
for (auto const & p: charHistogram)
{
std::cout << p.first << " : " << p.second << " ";
}
return 0;
}
查看cpp.sh 中的代碼
uj5u.com熱心網友回復:
添加到@codeling 答案的另一個選項。相同的想法,但不同的實作:
- 您可以使用陣列來計算使用過的字母。第一個陣列位置將告訴您“a”的出現次數,“b”的第二個位置,依此類推。
- 您可以擴展它以計算大寫字母和符號。
- 你也可以改變
std::array一個size_t counts[26]陣列。
[演示]
#include <array>
#include <iostream> // cout
#include <string>
int main()
{
const std::string s{"aaabbc"};
std::array<size_t, 26> counts{};
for (auto&& ch : s)
{
if (ch >='a' and ch <= 'z')
{
counts[ch - 'a'] ;
}
}
for (char i{0}; i < counts.size(); i)
{
if (counts[i])
{
std::cout << static_cast<char>('a' i) << ": " << counts[i] << "\n";
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/380758.html
上一篇:RabinKarp演算法負哈希
