Formatted question description: https://leetcode.ca/all/1957.html

1957. Delete Characters to Make Fancy String

Level

Easy

Description

A 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”.

Constraints:

  • 1 <= s.length <= 10^5
  • s consists only of lowercase English letters.

Solution

Loop over s and find the size of each group with consecutive equal characters. If a group has size less than three, than append all the characters to the result string. Otherwise, only append two of the characters to the result string. Finally, return the result string.

class Solution {
    public String makeFancyString(String s) {
        StringBuffer sb = new StringBuffer();
        int length = s.length();
        char prev = ' ';
        int count = 1;
        for (int i = 0; i < length; i++) {
            char curr = s.charAt(i);
            if (curr == prev)
                count++;
            else {
                count = 1;
                prev = curr;
            }
            if (count < 3)
                sb.append(curr);
        }
        return sb.toString();
    }
}

All Problems

All Solutions