String s formed by digits (
'0'
- '9'
) and '#'
. We want to map s
to English lowercase characters as follows:- Characters (
'a'
to'i')
are represented by ('1'
to'9'
) respectively.
- Characters (
'j'
to'z')
are represented by ('10#'
to'26#'
) respectively.
Example:
Input: str = "10#11#12" Output: "jkab"
Approach:
Java
public class DecryptString {
public static void main(String[] args) {
String str = "10#11#12";
String convert = freqAlphabets(str);
System.out.println(convert);
}
// convert to string based on feq
private static String freqAlphabets(String str) {
int cnt = 0;
String digit = "";
String decrypt = "";
// iterate till end of string
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
// if char is digit
if (Character.isDigit(c)) {
cnt++;
// if cnt>2 or digit are two
if (cnt > 2 || digit.length() == 2) {
// convert int to char
decrypt += (char) (Integer.parseInt(
String.valueOf(digit.charAt(0))) + 96);
digit = String.valueOf(digit.charAt(1));
cnt = 1;
}
digit += c;
} else {
// convert int to char
decrypt += (char) (Integer.parseInt(digit) + 96);
digit = "";
cnt = 0;
}
}
// pending length
if (digit.length() != 0) {
// for 10
if (Integer.parseInt(digit) > 10) {
for (int j = 0; j < digit.length(); j++) {
// convert char to int
decrypt += (char) (Integer.parseInt(
String.valueOf(digit.charAt(j))) + 96);
}
} else {
// convet char to int
decrypt += (char) (Integer.parseInt(digit) + 96);
}
}
return decrypt;
}
}
C++
#include <bits/stdc++.h>
using namespace std;
//function to deecrypt String from
//Alphabet to Integer Mapping
string freqAlphabets(string s)
{
map<string,string> mp;
for(int i=1;i<=9;i++)
mp[to_string(i)]='a'+i-1;
for(int i=10;i<=26;i++)
{
string x=to_string(i);
x+="#";
mp[x]=i-1+'a';
}
string res="";
int i=0,n=s.size();
while(i<n)
{
string str="";
if((i+2)<n)
{
if(s[i+2]=='#')
{
str+=s[i];
str+=s[i+1];
str+=s[i+2];
i+=3;
}
else
{
str+=s[i];
i++;
}
}
else
{
str+=s[i];
i++;
}
res+=mp[str];
}
return res;
}
int main()
{
string str="10#11#12";
string convert=freqAlphabets(str);
cout<<convert<<"\n";
return 0;
}
No comments:
Post a Comment