commit ea7b392996dc3799be46379040f025a988e8d6c3
parent 45a8af12d6d2f60e1efdba06d853aaff9055193f
Author: Jack Sangdahl <jack@pngu.org>
Date: Thu, 31 Oct 2024 18:12:11 -0600
1957. delete characters to make fancy string
Diffstat:
2 files changed, 62 insertions(+), 0 deletions(-)
diff --git a/delete_char_fancy_string.c b/delete_char_fancy_string.c
@@ -0,0 +1,30 @@
+// 1957. Delete Characters to Make Fancy String
+#include "leetcode.h"
+
+/*
+ * 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
+ */
+
+char *makeFancyString(char *s) {
+ int n = strlen(s);
+ if (n < 3)
+ return s;
+ int cnt = 1, j = 0;
+ for (int i = 1; i < n; i++) {
+ cnt = s[i] == s[i - 1] ? cnt + 1 : 1;
+ if (cnt <= 2)
+ s[++j] = s[i];
+ }
+ s[j + 1] = '\0';
+ return s;
+}
+
+int main() {
+ char *s1 = "leeetcode", *s2 = "aaabaaaa", *s3 = "aab";
+ printf("%s\n", makeFancyString(s1)); // expect: leetcode
+ printf("%s\n", makeFancyString(s2)); // expect: aabaa
+ printf("%s\n", makeFancyString(s3)); // expect: aab
+}
diff --git a/delete_char_fancy_string.py b/delete_char_fancy_string.py
@@ -0,0 +1,32 @@
+# 1957. Delete Characters to Make Fancy String
+
+"""
+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
+"""
+
+
+class Solution(object):
+ def makeFancyString(self, s):
+ """
+ :type s: str
+ :rtype: str
+ """
+ cnt, ans = 0, []
+ for i, j in enumerate(s):
+ if i > 0 and j == s[i - 1]:
+ cnt += 1
+ else:
+ cnt = 1
+ if cnt < 3:
+ ans.append(j)
+ return "".join(ans)
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.makeFancyString(s="leeetcode"))
+ print(obj.makeFancyString(s="aaabaaaa"))
+ print(obj.makeFancyString(s="aab"))