Welcome to Subscribe On Youtube
1957. Delete Characters to Make Fancy String
Description
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.
Solutions
-
class Solution { public String makeFancyString(String s) { StringBuilder ans = new StringBuilder(); for (char c : s.toCharArray()) { int n = ans.length(); if (n > 1 && ans.charAt(n - 1) == c && ans.charAt(n - 2) == c) { continue; } ans.append(c); } return ans.toString(); } }
-
class Solution { public: string makeFancyString(string s) { string ans = ""; for (char& c : s) { int n = ans.size(); if (n > 1 && ans[n - 1] == c && ans[n - 2] == c) continue; ans.push_back(c); } return ans; } };
-
class Solution: def makeFancyString(self, s: str) -> str: ans = [] for c in s: if len(ans) > 1 and ans[-1] == ans[-2] == c: continue ans.append(c) return ''.join(ans)
-
func makeFancyString(s string) string { ans := []rune{} for _, c := range s { n := len(ans) if n > 1 && ans[n-1] == c && ans[n-2] == c { continue } ans = append(ans, c) } return string(ans) }
-
class Solution { /** * @param String $s * @return String */ function makeFancyString($s) { $rs = ''; for ($i = 0; $i < strlen($s); $i++) { if ($s[$i] == $s[$i + 1] && $s[$i] == $s[$i + 2]) { continue; } else { $rs .= $s[$i]; } } return $rs; } }
-
function makeFancyString(s: string): string { const ans: string[] = []; for (const c of s) { const n = ans.length; if (n < 2 || c !== ans[n - 1] || c !== ans[n - 2]) { ans.push(c); } } return ans.join(''); }