Skip to content

1957. Delete Characters to Make Fancy String 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
 public:
  string makeFancyString(string s) {
    string ans;
    for (const char c : s)
      if (ans.length() < 2 || ans.back() != c || ans[ans.size() - 2] != c)
        ans.push_back(c);
    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
  public String makeFancyString(String s) {
    StringBuilder sb = new StringBuilder();
    for (char c : s.toCharArray())
      if (sb.length() < 2 || //
          sb.charAt(sb.length() - 1) != c || sb.charAt(sb.length() - 2) != c)
        sb.append(c);
    return sb.toString();
  }
}
1
2
3
4
5
6
7
class Solution:
  def makeFancyString(self, s: str) -> str:
    ans = []
    for c in s:
      if len(ans) < 2 or ans[-1] != c or ans[-2] != c:
        ans.append(c)
    return ''.join(ans)