carloscn / structstudy

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

leetcode2399: Check Distances Between Same Letters #392

Open carloscn opened 11 months ago

carloscn commented 11 months ago

Description

You are given a 0-indexed string s consisting of only lowercase English letters, where each letter in s appears exactly twice. You are also given a 0-indexed integer array distance of length 26.

Each letter in the alphabet is numbered from 0 to 25 (i.e. 'a' -> 0, 'b' -> 1, 'c' -> 2, ... , 'z' -> 25).

In a well-spaced string, the number of letters between the two occurrences of the ith letter is distance[i]. If the ith letter does not appear in s, then distance[i] can be ignored.

Return true if s is a well-spaced string, otherwise return false.

Example 1:

Input: s = "abaccb", distance = [1,3,0,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] Output: true Explanation:

Example 2:

Input: s = "aa", distance = [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] Output: false Explanation:

Constraints:

2 <= s.length <= 52 s consists only of lowercase English letters. Each letter appears in s exactly twice. distance.length == 26 0 <= distance[i] <= 50

carloscn commented 11 months ago

Analysis

pub fn check_distances(s: &str, distance: Vec<i32>) -> bool
{
    let mut ret:bool = false;
    if s.len() < 1 || distance.len() < 1 {
        return ret;
    }

    let dup_s:Vec<char> = s.chars().collect();
    let mut dup_v:Vec<i32> = vec![];

    for i in 0..dup_s.len() {
        let target = dup_s[i];
        for j in (i + 1)..dup_s.len() {
            if dup_s[j] == target {
                dup_v.push((j - i - 1) as i32);
            }
        }
    }

    for i in 0..distance.len() {
        if (i < dup_v.len() && dup_v[i] != distance[i]) {
            return false;
        }
    }

    ret = true;

    return ret;
}
carloscn commented 11 months ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1170956 https://github.com/carloscn/structstudy/commit/6dbfe500d747b26e282edd09cf8c67fcaf168f73