carloscn / structstudy

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

leetcode2490: Circular Sentence #406

Open carloscn opened 11 months ago

carloscn commented 11 months ago

Description

A sentence is a list of words that are separated by a single space with no leading or trailing spaces.

For example, "Hello World", "HELLO", "hello world hello world" are all sentences. Words consist of only uppercase and lowercase English letters. Uppercase and lowercase English letters are considered different.

A sentence is circular if:

The last character of a word is equal to the first character of the next word. The last character of the last word is equal to the first character of the first word. For example, "leetcode exercises sound delightful", "eetcode", "leetcode eats soul" are all circular sentences. However, "Leetcode is cool", "happy Leetcode", "Leetcode" and "I like Leetcode" are not circular sentences.

Given a string sentence, return true if it is circular. Otherwise, return false.

Example 1:

Input: sentence = "leetcode exercises sound delightful" Output: true Explanation: The words in sentence are ["leetcode", "exercises", "sound", "delightful"].

Example 2:

Input: sentence = "eetcode" Output: true Explanation: The words in sentence are ["eetcode"].

Example 3:

Input: sentence = "Leetcode is cool" Output: false Explanation: The words in sentence are ["Leetcode", "is", "cool"].

Constraints:

1 <= sentence.length <= 500 sentence consist of only lowercase and uppercase English letters and spaces. The words in sentence are separated by a single space. There are no leading or trailing spaces.

carloscn commented 11 months ago

Analysis

pub fn is_circular_sentence(sentence: &str) -> bool
{
    if sentence.is_empty() {
        return false;
    }

    let input_vec:Vec<String> = sentence.split(' ').map(|x| x.to_string()).collect();

    let mut i:usize = 0;
    let mut j:usize = 0;
    let mut sum_vec:Vec<char> = vec![];
    loop {
        let mut e_vec:Vec<char> = input_vec[i].chars().collect();
        if sum_vec.is_empty() {
            sum_vec.append(&mut e_vec);
        } else {
            if sum_vec[sum_vec.len() - 1] != e_vec[0] {
                return false;
            }
            sum_vec.append(&mut e_vec);
        }
        j += 1;
        i = (i + 1) % input_vec.len();
        if j > input_vec.len() + 1 {
            break;
        }
    }

    return true;
}
carloscn commented 11 months ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1171371 https://github.com/carloscn/structstudy/commit/f1698245abb7e31e17b3d70f8020adf24555e5a6