Compress the String

Given a string S of lowercase English alphabets of length N. You need to compress the string with the following rules:

1. Convert the first letter to the uppercase
2. Convert the substring consisting of all the consonants to the length of this substring (e.g. abcde to a3e)
3. Remove the consecutive duplicate vowels (e.g. aaaeiia to aeia)

Note: The first letter will not follow rules 2 and 3.

Example:

Input:  n = 10, s = "aaabcdefee"
Output: Aa3e1e

Approach

C++

#include <bits/stdc++.h>
using namespace std;

bool consonent(char c)
{
    if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
        return false;
    return true;
}

string compressString(int nstring s)
{

    int i = 1;
    string res = "";
    if (s[0] >= 'a' && s[0] <= 'z')
        res += s[0] - 32;
    else
        res += s[0];
    while (i < n)
    {

        if (consonent(s[i]) == false)
        {
            while (i < n - 1 && s[i] == s[i + 1])
                i++;
            res += s[i];
            i++;
        }
        else
        {
            int cnt = 0;
            while (i < n && consonent(s[i]))
            {
                cnt++;
                i++;
            }
            ostringstream str1;
            str1 << cnt;
            string strin = str1.str();

            res += strin;
        }
    }
    return res;
}
int main()
{
    int n = 10;
    string s = "aaabcdefee";

    cout << compressString(ns<< "\n";

    return 0;
}


No comments:

Post a Comment