python 游程编码_游程编码(字符串中字母的查找/打印频率)

python 游程编码

Problem description

问题描述

Write a program that counts frequency of each letter in the string (string consists lowercase letters only).

编写一个程序来计算字符串中每个字母的频率 (字符串仅包含小写字母)。

Solution:

解:

Algorithm

算法

  1. Initialize an array of 26 elements for each letter (a-z) to 0. (array[26]={0})

    将每个字母(az)初始化为26个元素的数组,以将其设置为0。( array [26] = {0} )

  2. 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] ++ )

  3. 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 游程编码

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值