Q:

Run-length encoding (find/print frequency of letters in a string)

belongs to collection: Interview coding problems/challenges

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

#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;
}

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Given two strings, check whether two given strings... >>