在C++中使用unordered_map表示字符串中每个字符的频率

2021年4月18日19:25:53 发表评论 645 次浏览

给定一个字符串str, 任务是使用unordered_mapinC++++ STL.

例子:

输入:str ="geeksforgeeks"
输出:
r 1
e 4
s 2
g 2
k 2
f 1
o 1
输入:str ="programming"
输出:
n 1
i 1
p 1
o 1
r 2
a 1
g 2
m 2

方法:

  1. 遍历给定字符串的每个字符str.
  2. 检查当前字符是否存在于unordered_map或不。
  3. 如果存在, 则更新当前字符的频率, 否则插入频率为1的字符, 如下所示:
if(M.find(s[i])==M.end()) {
    M.insert(make_pair{s[i], 1});
}
else {
    M展开]++;
}

4.遍历unordered_map并打印每个字符的频率作为映射值。

下面是上述方法的实现:

CPP

//C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
void printFrequency(string str)
{
     //Define an unordered_map
     unordered_map<char , int> M;
 
     //Traverse string str check if
     //current character is present
     //or not
     for ( int i = 0; str[i]; i++)
     {
         //If the current characters
         //is not found then insert
         //current characters with
         //frequency 1
         if (M.find(str[i]) == M.end())
         {
             M.insert(make_pair(str[i], 1));
         }
 
         //Else update the frequency
         else
         {
             M[str[i]]++;
         }
     }
 
     //Traverse the map to print the
     //frequency
     for ( auto & it : M) {
         cout <<it.first <<' ' <<it.second <<'\n' ;
     }
}
 
//Driver Code
int main()
{
     string str = "lsbin" ;
 
     //Function call
     printFrequency(str);
     return 0;
}

输出如下

r 1
e 4
s 2
g 2
k 2
f 1
o 1

被认为是行业中最受欢迎的技能之一, 我们拥有自己的编码基础C++ STL通过激烈的问题解决过程来训练和掌握这些概念。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: