Skip to content

Latest commit

 

History

History
165 lines (131 loc) · 3.91 KB

File metadata and controls

165 lines (131 loc) · 3.91 KB
comments difficulty edit_url rating source tags
true
Easy
1357
Biweekly Contest 58 Q1
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

Python3

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)

Java

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

C++

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

Go

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

PHP

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