返回介绍

solution / 1900-1999 / 1957.Delete Characters to Make Fancy String / README_EN

发布于 2024-06-17 01:03:12 字数 3823 浏览 0 评论 0 收藏 0

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

Solution 1

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)
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;
  }
};
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;
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文