carloscn / structstudy

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

leetcode2451: Odd String Difference #400

Open carloscn opened 1 year ago

carloscn commented 1 year ago

Description

You are given an array of equal-length strings words. Assume that the length of each string is n.

Each string words[i] can be converted into a difference integer array difference[i] of length n - 1 where difference[i][j] = words[i][j+1] - words[i][j] where 0 <= j <= n - 2. Note that the difference between two letters is the difference between their positions in the alphabet i.e. the position of 'a' is 0, 'b' is 1, and 'z' is 25.

For example, for the string "acb", the difference integer array is [2 - 0, 1 - 2] = [2, -1]. All the strings in words have the same difference integer array, except one. You should find that string.

Return the string in words that has different difference integer array.

Example 1:

Input: words = ["adc","wzy","abc"] Output: "abc" Explanation:

Example 2:

Input: words = ["aaa","bob","ccc","ddd"] Output: "bob" Explanation: All the integer arrays are [0, 0] except for "bob", which corresponds to [13, -13].

Constraints:

3 <= words.length <= 100 n == words[i].length 2 <= n <= 20 words[i] consists of lowercase English letters.

carloscn commented 1 year ago

Analysis

pub fn odd_string(words: Vec<&str>) -> String
{
    if words.len() < 1 {
        return String::new();
    }

    let mut rom:Vec<(Vec<i32>, String)> = vec![];

    for i in 0..words.len() {
        let mut vp:Vec<char> = words[i].chars().collect();
        let mut cv:Vec<i32> = vec![0;2];
        cv[0] = (vp[1] as i8 - vp[0] as i8) as i32;
        cv[1] = (vp[2] as i8 - vp[1] as i8) as i32;
        rom.push(((cv, words[i].to_string())));
    }

    for item in &rom {
        let is_unique = rom.iter().filter(|&x| x.0 == item.0).count() == 1;
        if is_unique {
            return item.clone().1;
        }
    }

    return String::new();
}
carloscn commented 1 year ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1171191 https://github.com/carloscn/structstudy/commit/9cf9f5a0c42bc27c15f31dd03e662c1216c25c86