carloscn / structstudy

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

leetcode2085: Count Common Words With One Occurrence #335

Open carloscn opened 1 year ago

carloscn commented 1 year ago

Description

Given two string arrays words1 and words2, return the number of strings that appear exactly once in each of the two arrays.

Example 1:

Input: words1 = ["leetcode","is","amazing","as","is"], words2 = ["amazing","leetcode","is"] Output: 2 Explanation:

Example 2:

Input: words1 = ["b","bb","bbb"], words2 = ["a","aa","aaa"] Output: 0 Explanation: There are no strings that appear in each of the two arrays.

Example 3:

Input: words1 = ["a","ab"], words2 = ["a","a","a","ab"] Output: 1 Explanation: The only string that appears exactly once in each of the two arrays is "ab".

Constraints:

1 <= words1.length, words2.length <= 1000 1 <= words1[i].length, words2[j].length <= 30 words1[i] and words2[j] consists only of lowercase English letters.

carloscn commented 1 year ago

Analysis

fn delete_dup_elements(vec:&mut Vec<&str>)
{
    let mut i = 0;
    while i < vec.len() {
        let current_item = &vec[i].clone();
        if vec.iter().filter(|&&item| item == *current_item).count() > 1 {
            vec.retain(|&item| item != *current_item);
        } else {
            i += 1;
        }
    }
}

pub fn count_words(words1: Vec<&str>, words2: Vec<&str>) -> i32
{
    let mut ret:i32 = 0;

    if words1.len() < 1 || words2.len() < 1 {
        return ret;
    }

    let mut wp1 = words1.clone();
    let mut wp2 = words2.clone();

    delete_dup_elements(&mut wp1);
    delete_dup_elements(&mut wp2);

    for e in &wp1 {
        for k in &wp2 {
            if *e == *k {
                ret += 1;
            }
        }
    }

    return ret;
}
carloscn commented 1 year ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1168734 https://github.com/carloscn/structstudy/commit/2e624a27d661c46ecc93078d0ccec09bcf5f064a