Leetcode 1957. Delete Characters to Make Fancy String
Given a string s
, delete the minimum number of characters from s
such that no three consecutive characters are the same.
Return the final string after the deletion.
s.length
<= 10^5.StringBuilder
to construct the resultant string.StringBuilder
to ensure no three consecutive characters are the same.public class FancyString {
public static String makeFancyString(String s) {
StringBuilder result = new StringBuilder();
for (char c : s.toCharArray()) {
int len = result.length();
// Check if we need to append this character or not
if (len >= 2 && result.charAt(len - 1) == c && result.charAt(len - 2) == c) {
continue;
}
result.append(c);
}
return result.toString();
}
public static void main(String[] args) {
String s1 = "leeetcode";
String s2 = "aaabaaaa";
String s3 = "aab";
System.out.println(makeFancyString(s1)); // Output: "leetcode"
System.out.println(makeFancyString(s2)); // Output: "aabaa"
System.out.println(makeFancyString(s3)); // Output: "aab"
}
}
n
is the length of the string. We traverse the input string once.StringBuilder
if no characters are removed.This solution is efficient and should work within the constraints provided.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?