carloscn / structstudy

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

leetcode2062: Count Vowel Substrings of a String #332

Open carloscn opened 1 year ago

carloscn commented 1 year ago

Description

A substring is a contiguous (non-empty) sequence of characters within a string.

A vowel substring is a substring that only consists of vowels ('a', 'e', 'i', 'o', and 'u') and has all five vowels present in it.

Given a string word, return the number of vowel substrings in word.

Example 1:

Input: word = "aeiouu" Output: 2 Explanation: The vowel substrings of word are as follows (underlined):

Example 2:

Input: word = "unicornarihan" Output: 0 Explanation: Not all 5 vowels are present, so there are no vowel substrings.

Example 3:

Input: word = "cuaieuouac" Output: 7 Explanation: The vowel substrings of word are as follows (underlined):

Constraints:

1 <= word.length <= 100 word consists of lowercase English letters only.

carloscn commented 1 year ago

Code

fn is_vowel(c:char) -> bool
{
    if c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' {
        return true;
    }

    return false;
}

fn is_contiguous(w:&Vec<char>, start:usize, end:usize) -> bool
{
    let copied_slice = &w[start..=end];
    let mut a_f:bool = false;
    let mut e_f:bool = false;
    let mut i_f:bool = false;
    let mut o_f:bool = false;
    let mut u_f:bool = false;

    for e in copied_slice {
        if *e == 'a' {
            a_f = true;
        } else if *e == 'e' {
            e_f = true;
        } else if *e == 'i' {
            i_f = true;
        } else if *e == 'o' {
            o_f = true;
        } else if *e == 'u' {
            u_f = true;
        } else {
            return false;
        }
    }

    return a_f && e_f && i_f && o_f && u_f;
}

pub fn count_vowel_substrings(word: &str) -> i32
{
    let mut ret:i32 = 0;

    if word.len() < 5 {
        return ret;
    }

    let w_v:Vec<char> = word.chars().collect();
    for i in 0..w_v.len() - 4 {
        let mut contiguous_count = 0_i32;
        for j in i..w_v.len() {
            if is_vowel(w_v[j]) {
                contiguous_count += 1;
            } else {
                contiguous_count = 0;
            }
            if contiguous_count >= 5 {
                if is_contiguous(&w_v, i, j) {
                    ret += 1;
                }
            }
        }
    }

    return ret;
}
carloscn commented 1 year ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1168601 https://github.com/carloscn/structstudy/commit/acc1d0bb0409fd2213117bca478ddcdcdf47b3d8