carloscn / structstudy

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

leetcode1974: Minimum Time to Type Word Using Special Typewriter #315

Open carloscn opened 1 year ago

carloscn commented 1 year ago

Description

There is a special typewriter with lowercase English letters 'a' to 'z' arranged in a circle with a pointer. A character can only be typed if the pointer is pointing to that character. The pointer is initially pointing to the character 'a'.

image

Each second, you may perform one of the following operations:

Move the pointer one character counterclockwise or clockwise. Type the character the pointer is currently on. Given a string word, return the minimum number of seconds to type out the characters in word.

Example 1:

Input: word = "abc" Output: 5 Explanation: The characters are printed as follows:

Example 2:

Input: word = "bza" Output: 7 Explanation: The characters are printed as follows:

Example 3:

Input: word = "zjpc" Output: 34 Explanation: The characters are printed as follows:

Constraints:

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

carloscn commented 1 year ago

Analysis

fn caculate_min_distance(a:char, b:char) -> i32
{
    let a_u = a as i32;
    let b_u = b as i32;

    return i32::abs(a_u - b_u)
           .min(26 - i32::abs(a_u - b_u));
}

pub fn min_time_to_type(word: &str) -> i32
{
    if word.len() < 1 {
        return 0;
    }

    let mut ret:i32 = 0;
    let mut w_v:Vec<char> = word.chars().collect();

    w_v.insert(0, 'a');

    for i in 0..w_v.len() - 1 {
        ret += caculate_min_distance(w_v[i], w_v[i + 1]);
    }

    return ret + w_v.len() as i32 - 1;
}
carloscn commented 1 year ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1168019 https://github.com/carloscn/structstudy/commit/1ed4497520f05ba18deaad4c627e8f9dba36d9d1