carloscn / structstudy

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

leetcode2185: Counting Words With a Given Prefix #354

Open carloscn opened 1 year ago

carloscn commented 1 year ago

Description

You are given an array of strings words and a string pref.

Return the number of strings in words that contain pref as a prefix.

A prefix of a string s is any leading contiguous substring of s.

Example 1:

Input: words = ["pay","attention","practice","attend"], pref = "at" Output: 2 Explanation: The 2 strings that contain "at" as a prefix are: "attention" and "attend".

Example 2:

Input: words = ["leetcode","win","loops","success"], pref = "code" Output: 0 Explanation: There are no strings that contain "code" as a prefix.

Constraints:

1 <= words.length <= 100 1 <= words[i].length, pref.length <= 100 words[i] and pref consist of lowercase English letters.

carloscn commented 1 year ago

Analysis

fn is_same_pref(in_str:&str, pref: &str) -> bool
{
    let in_pref = in_str.get(0..pref.len());

    match (in_pref, pref) {
        (Some(in_pref), pref) => in_pref == pref,
        _ => false,
    }
}

pub fn prefix_count(words: Vec<&str>, pref: &str) -> i32
{
    let mut ret:i32 = 0;

    if words.len() < 1 || pref.len() < 1 {
        return ret;
    }

    for e in words {
        if is_same_pref(e, pref) {
            ret += 1;
        }

    }

    return ret;
}
carloscn commented 1 year ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1169690 https://github.com/carloscn/structstudy/commit/1aca913668c7a260e566f59e0c0df323a8785653