carloscn / structstudy

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

leetcode2506: Count Pairs Of Similar Strings #409

Open carloscn opened 1 year ago

carloscn commented 1 year ago

Description

You are given a 0-indexed string array words.

Two strings are similar if they consist of the same characters.

For example, "abca" and "cba" are similar since both consist of characters 'a', 'b', and 'c'. However, "abacba" and "bcfd" are not similar since they do not consist of the same characters. Return the number of pairs (i, j) such that 0 <= i < j <= word.length - 1 and the two strings words[i] and words[j] are similar.

Example 1:

Input: words = ["aba","aabb","abcd","bac","aabc"] Output: 2 Explanation: There are 2 pairs that satisfy the conditions:

Example 2:

Input: words = ["aabb","ab","ba"] Output: 3 Explanation: There are 3 pairs that satisfy the conditions:

Example 3:

Input: words = ["nba","cba","dba"] Output: 0 Explanation: Since there does not exist any pair that satisfies the conditions, we return 0.

Constraints:

1 <= words.length <= 100 1 <= words[i].length <= 100 words[i] consist of only lowercase English letters.

carloscn commented 1 year ago

Analysis


fn string_same(a:&str, b:&str) -> bool
{
    let mut a_vec:Vec<char> = a.chars().collect();
    let mut b_vec:Vec<char> = b.chars().collect();

    a_vec.sort();
    b_vec.sort();

    a_vec.dedup();
    b_vec.dedup();

    return a_vec == b_vec;
}

pub fn similar_pairs(words: Vec<&str>) -> i32
{
    let mut ret:i32 = 0;
    if words.len() < 1 {
        return ret;
    }

    let mut max_count:i32 = i32::MIN;
    for i in 0..words.len() {
        let mut count:i32 = 0;
        for j in 0..words.len() {
            if j != i && string_same(words[i], words[j]) {
                count += 1;
            }
        }
        max_count = max_count.max(count);
    }

    if max_count != 0 {
        ret += 1;
    }
    ret += max_count;

    return ret;
}
carloscn commented 1 year ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1171556 https://github.com/carloscn/structstudy/commit/0761be069efe1bd6544a5c90c54e5a2b3d2ab378