carloscn / structstudy

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

leetcode2053: Kth Distinct String in an Array #330

Open carloscn opened 1 year ago

carloscn commented 1 year ago

Decription

A distinct string is a string that is present only once in an array.

Given an array of strings arr, and an integer k, return the kth distinct string present in arr. If there are fewer than k distinct strings, return an empty string "".

Note that the strings are considered in the order in which they appear in the array.

Example 1:

Input: arr = ["d","b","c","b","c","a"], k = 2 Output: "a" Explanation: The only distinct strings in arr are "d" and "a". "d" appears 1st, so it is the 1st distinct string. "a" appears 2nd, so it is the 2nd distinct string. Since k == 2, "a" is returned.

Example 2:

Input: arr = ["aaa","aa","a"], k = 1 Output: "aaa" Explanation: All strings in arr are distinct, so the 1st string "aaa" is returned.

Example 3:

Input: arr = ["a","b","a"], k = 3 Output: "" Explanation: The only distinct string is "b". Since there are fewer than 3 distinct strings, we return an empty string "".

Constraints:

1 <= k <= arr.length <= 1000 1 <= arr[i].length <= 5 arr[i] consists of lowercase English letters.

carloscn commented 1 year ago

Analysis

pub fn kth_distinct(arr: Vec<&str>, k: i32) -> String
{
    let mut ret:String = String::new();

    if arr.len() < 1 || k < 1 {
        return ret;
    }

    let mut arr_vec:Vec<&str> = arr.clone();
    let mut fin_vec:Vec<&str> = vec![];
    let mut i:usize = 0;

    arr_vec.sort();
    while i < arr_vec.len() {
        if fin_vec.is_empty() || fin_vec[fin_vec.len() - 1] != arr_vec[i] {
            fin_vec.push(arr_vec[i]);
        } else {
            fin_vec.pop();
        }
        i += 1;
    }

    if (k as usize) <= fin_vec.len() {
        ret = fin_vec[k as usize - 1].to_string();
    }

    return ret;
}
carloscn commented 1 year ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1168565 https://github.com/carloscn/structstudy/commit/1b5ca74ccb5d422a0c616bc84917087294a7ec42