python 游程编码
Problem description
问题描述
Write a program that counts frequency of each letter in the string (string consists lowercase letters only).
编写一个程序来计算字符串中每个字母的频率 (字符串仅包含小写字母)。
Solution:
解:
Algorithm
算法
Initialize an array of 26 elements for each letter (a-z) to 0. (array[26]={0})
将每个字母(az)初始化为26个元素的数组,以将其设置为0。( array [26] = {0} )
Scan the entire string and for each string element check the letter and increase the frequency in array by using ASCII value. (array[str[i]-'a']++)
扫描整个字符串,并为每个字符串元素检查字母,并使用ASCII值增加数组中的频率。 ( array [str [i]-'a'] ++ )
Like in
像
str="aaabbccccddef",
str =“ aaabbccccddef” ,
str [3] ='b'
str [3] ='b'
Thus, and
因此,
str [2]-'a'=1
str [2]-'a'= 1
Thus it increases the frequency of
因此,它增加了频率
'b' by 1 (array [str [3]-'a'] turns to be array [1] ++)
“ b”乘以1(数组[str [3]-'a']变成数组[1] ++ )
Finally print the letter with their respective frequencies. This is the encoded string.
最后,以相应的频率打印字母。 这是编码的字符串。
C ++程序查找/打印字符串中字母的频率 (C++ program to find/print frequency of letters in a string)
#include <bits/stdc++.h>
using namespace std;
void freq(string s){
//array to store frequency of 26 characters,initialized to 0
int arr[26]={0};
for(int i=0;i<s.length();i++){
// s[i] is the ascii value of the letter at index i & 'a'
//also gives the ascii value of a, in this way we are
//checking which alphabet is at index i and increasing its frequency
arr[s[i]-'a']++;
}
for(int i=0;i<26;i++){
if(arr[i]!=0)
printf("%d%c",arr[i],'a'+i);
}
cout<<endl;
}
int main(){
string s;
cout<<"enter string\n";
cin>>s;
cout<<"encoded string is : "<<endl;
freq(s);
return 0;
}
Output
输出量
enter string
aaaabbcccccddf
encoded string is :
4a2b5c2d1f
Recommended posts
推荐的帖子
翻译自: https://www.includehelp.com/icp/run-length-encoding-print-frequency-of-letters-in-a-string.aspx
python 游程编码