diff options
-rw-r--r-- | delete_char_fancy_string.c | 30 | ||||
-rw-r--r-- | delete_char_fancy_string.py | 32 |
2 files changed, 62 insertions, 0 deletions
diff --git a/delete_char_fancy_string.c b/delete_char_fancy_string.c new file mode 100644 index 0000000..9fe69ee --- /dev/null +++ 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 new file mode 100644 index 0000000..4dd8e91 --- /dev/null +++ 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")) |