Delete Characters to Make Fancy String
Problem
Remove minimum chars so s has no three consecutive identical characters.
s = "leeetcode""leetcode"def make_fancy_string(s):
out = []
for c in s:
if len(out) >= 2 and out[-1] == out[-2] == c:
continue
out.append(c)
return ''.join(out)
function makeFancyString(s) {
let out = '';
for (const c of s) {
if (out.length >= 2 && out[out.length-1] === c && out[out.length-2] === c) continue;
out += c;
}
return out;
}
class Solution {
public String makeFancyString(String s) {
StringBuilder sb = new StringBuilder();
for (char c : s.toCharArray()) {
int n = sb.length();
if (n >= 2 && sb.charAt(n-1) == c && sb.charAt(n-2) == c) continue;
sb.append(c);
}
return sb.toString();
}
}
string makeFancyString(string s) {
string out;
for (char c : s) {
int n = out.size();
if (n >= 2 && out[n-1] == c && out[n-2] == c) continue;
out += c;
}
return out;
}
Explanation
A "fancy" string is one where no character appears three times in a row. The trick is that we never have to look at the original string twice — we just build the answer character by character and only keep a letter if it does not create a run of three.
We keep a growing result called out. For each incoming character c, we peek at the last two characters we already kept. If both of them equal c, adding c would make three in a row, so we continue (skip it). Otherwise we append c.
This works because the only way to ever get three identical characters is to have two of them already at the end and then add a matching third — and that is exactly the case we block.
Example: s = "leeetcode". We keep l, e, e. The third e sees that out ends in ee, so it is dropped. The rest pass through, giving "leetcode".
Because each character is examined once and the peek is constant work, the whole scan is fast and linear.