Delete Characters to Make Fancy String

fancy string is a string where no three consecutive characters are equal.

Given a string s, delete the minimum possible number of characters from s to make it fancy.

Return the final string after the deletion. It can be shown that the answer will always be unique.

Example 1:

Input: s = "leeetcode"
Output: "leetcode"
Explanation:
Remove an 'e' from the first group of 'e's to create "leetcode".
No three consecutive characters are equal, so return "leetcode".

Example 2:

Input: s = "aaabaaaa"
Output: "aabaa"
Explanation:
Remove an 'a' from the first group of 'a's to create "aabaaaa".
Remove two 'a's from the second group of 'a's to create "aabaa".
No three consecutive characters are equal, so return "aabaa".

Example 3:

Input: s = "aab"
Output: "aab"
Explanation: No three consecutive characters are equal, so return "aab".

Approach

Java

public class MakeFancyString {
    public static void main(String[] args) {

        String s = "aaabaaaa";

        System.out.println(makeFancyString(s));

    }

    static String makeFancyString(String s) {

        String res = "";
        res += s.charAt(0);
        int cnt = 1;
        for (int i = 1; i < s.length(); i++) {
            if (s.charAt(i) == s.charAt(i - 1))
                cnt++;
            else
                cnt = 1;
            if (cnt < 3)
                res += s.charAt(i);
        }

        return res;
    }

}

C++

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

string makeFancyString(string s)
{

    string res = "";
    res += s[0];
    int cnt = 1;
    for (int i = 1i < s.size(); i++)
    {
        if (s[i] == s[i - 1])
            cnt++;
        else
            cnt = 1;
        if (cnt < 3)
            res += s[i];
    }

    return res;
}
int main()
{
    string s = "aaabaaaa";

    cout << makeFancyString(s<< "\n";

    return 0;
}


No comments:

Post a Comment