Skip to content

Latest commit

 

History

History
73 lines (57 loc) · 2.21 KB

README.md

File metadata and controls

73 lines (57 loc) · 2.21 KB

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 <= 105
  • s consists only of lowercase English letters.

Companies:
Wayfair

Related Topics:
String

Solution 1.

// OJ: https://leetcode.com/problems/delete-characters-to-make-fancy-string/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
    string makeFancyString(string s) {
        int i = 0, j = 0, N = s.size();
        while (i < N) {
            int start = i;
            while (i < N && s[i] == s[start]) {
                if (i - start < 2) s[j++] = s[i];
                ++i;
            }
        }
        s.resize(j);
        return s;
    }
};