Encrypt the string - 1 Solution in cpp
Encrypt the string - 1 Solution in cpp
GfG problem solution in cpp
Bingu was testing all the strings he had at his place and found that most of them were prone to a vicious attack by Banju, his arch-enemy. Bingu decided to encrypt all the strings he had, by the following method. Every substring of identical letters is replaced by a single instance of that letter followed by the number of occurrences of that letter. Then, the string thus obtained is further encrypted by reversing it.
Example 1:
Input:
s = "aabc"
Output: 1c1b2a
Explanation: aabc
Step1: a2b1c1
Step2: 1c1b2acode;-
// { Driver Code Starts
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution{
public:
string reverse(string s){
int i=0;
int j=s.length()-1;
while(i<j){
swap(s[i++], s[j--]);
}
return s;
}
string encryptString(string s){
int i=0;
int n = s.length();
string s1 = "";
while (i<n){
int j = i+1;
while(j<n && s[i] == s[j]){
j++;
}
//nikal jyega agr nhi match kiya previous waala se toh
s1.push_back(s[i]); //store char
int count =0;
count = j-i;
if (count > 1){
string cnt = to_string(count); //converted integer to string
for(char ch: cnt)
s1.push_back(ch); //string count store kr liya
}
if(count ==1){
s1.push_back('1');
}
i=j;
}
return reverse(s1);
}
};
// { Driver Code Starts.
int main()
{
int t;
cin>>t;
while(t--){
string s;
cin>>s;
Solution ob;
string ans = ob.encryptString(s);
cout<<ans<<endl;
}
}
// } Driver Code Ends
Comments
Post a Comment