carloscn / structstudy

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

leetcode2273: Find Resultant Array After Removing Anagrams #372

Open carloscn opened 11 months ago

carloscn commented 11 months ago

Description

You are given a 0-indexed string array words, where words[i] consists of lowercase English letters.

In one operation, select any index i such that 0 < i < words.length and words[i - 1] and words[i] are anagrams, and delete words[i] from words. Keep performing this operation as long as you can select an index that satisfies the conditions.

Return words after performing all operations. It can be shown that selecting the indices for each operation in any arbitrary order will lead to the same result.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase using all the original letters exactly once. For example, "dacb" is an anagram of "abdc".

Example 1:

Input: words = ["abba","baba","bbaa","cd","cd"] Output: ["abba","cd"] Explanation: One of the ways we can obtain the resultant array is by using the following operations:

Example 2:

Input: words = ["a","b","c","d","e"] Output: ["a","b","c","d","e"] Explanation: No two adjacent strings in words are anagrams of each other, so no operations are performed.

Constraints:

1 <= words.length <= 100 1 <= words[i].length <= 10 words[i] consists of lowercase English letters.

carloscn commented 11 months ago

Analysis

fn is_anagram(str1:&str, str2:&str) -> bool
{
    if str1.len() != str2.len() {
        return false;
    }

    let mut chars1 = str1.chars().collect::<Vec<char>>();
    let mut chars2 = str2.chars().collect::<Vec<char>>();

    chars1.sort();
    chars2.sort();

    return chars1 == chars2;
}

pub fn remove_anagrams(words: Vec<&str>) -> Vec<String>
{
    if words.len() < 1 {
        return vec![];
    }

    let mut words_dup: Vec<&str> = words.clone();
    let mut i:usize = 0;

    while i < words_dup.len() - 1 {
        let mut j:usize = i + 1;
        while j < words_dup.len() {
            if is_anagram(words_dup[i], words_dup[j]) {
                words_dup.remove(j);
                j -= 1;
            }
            j += 1;
        }
        i += 1;
    }

    return words_dup.into_iter().map(|x| x.to_string()).collect();
}
carloscn commented 11 months ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1170462 https://github.com/carloscn/structstudy/commit/08ed116fe5d49d64073ed4da0909c302620d0add