carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

leetcode1957: Delete Characters to Make Fancy String #312

Open carloscn opened 1 year ago

carloscn commented 1 year ago

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.

carloscn commented 1 year ago

Analysis

pub fn make_fancy_string(s: &str) -> String
{
    if s.len() < 1 {
        return s.to_string();
    }

    let mut s_v:Vec<char> = s.chars().collect();
    let mut c:usize = 1;

    s_v.push(' ');
    let len = s_v.len();
    for i in 0..len - 1 {
        if s_v[i] == s_v[i + 1] {
            c += 1;
        } else {
            if c >= 3 {
                for j in 0..c - 2 {
                    s_v[i - j] = ' ';
                }
            }
            c = 1;
        }
    }

    return s_v.into_iter().filter(|x| *x != ' ').collect();
}
carloscn commented 1 year ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1167798 https://github.com/carloscn/structstudy/commit/a605408a08528a422584439d19d523cd17774361