carloscn / structstudy

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

leetcode821:字符的最短距离(shortest_distance_to_a_character_821) #134

Open carloscn opened 1 year ago

carloscn commented 1 year ago

问题描述

给你一个字符串 s 和一个字符 c ,且 c 是 s 中出现过的字符。

返回一个整数数组 answer ,其中 answer.length == s.length 且 answer[i] 是 s 中从下标 i 到离它 最近 的字符 c 的 距离 。

两个下标 i 和 j 之间的 距离 为 abs(i - j) ,其中 abs 是绝对值函数。

示例 1: 输入:s = "loveleetcode", c = "e" 输出:[3,2,1,0,1,0,0,1,2,2,1,0] 解释:字符 'e' 出现在下标 3、5、6 和 11 处(下标从 0 开始计数)。 距下标 0 最近的 'e' 出现在下标 3 ,所以距离为 abs(0 - 3) = 3 。 距下标 1 最近的 'e' 出现在下标 3 ,所以距离为 abs(1 - 3) = 2 。 对于下标 4 ,出现在下标 3 和下标 5 处的 'e' 都离它最近,但距离是一样的 abs(4 - 3) == abs(4 - 5) = 1 。 距下标 8 最近的 'e' 出现在下标 6 ,所以距离为 abs(8 - 6) = 2 。

示例 2: 输入:s = "aaab", c = "b" 输出:[3,2,1,0]

提示: 1 <= s.length <= 104 s[i] 和 c 均为小写英文字母 题目数据保证 c 在 s 中至少出现一次

来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/shortest-distance-to-a-character

carloscn commented 1 year ago

问题分析

C语言版本

static int32_t shortest_distance(const char *in_str, char c, int32_t *array)
{
    int32_t ret = 0;
    size_t in_len = 0;
    size_t *c_index = NULL;
    size_t c_len = 0;
    size_t i = 0;
    size_t j = 0;
    size_t d = 0, min_d = ~0;

    UTILS_CHECK_PTR(in_str);
    UTILS_CHECK_PTR(array);
    UTILS_CHECK_LEN(in_len = strlen(in_str));

    c_index = (size_t *)calloc(sizeof(size_t), in_len);
    UTILS_CHECK_PTR(c_index);

    for (i = 0; i < in_len; i ++) {
        if (c == in_str[i]) {
            c_index[c_len] = i;
            c_len ++;
        }
    }
    UTILS_CHECK_LEN(c_len);

    for (i = 0; i < in_len; i ++) {
        for (j = 0; j < c_len; j ++) {
            d = utils_int32_abs((int32_t)i - (int32_t)c_index[j]);
            min_d = d < min_d ? d : min_d;
        }
        array[i] = min_d;
        min_d = ~0;
    }

finish:
    return ret;
}

Rust版本

fn shortest_distance(in_str:&String, c:char) -> Result<Vec<i32>, &'static str>
{
    let in_len:usize = in_str.len();
    let in_chars = in_str.chars();
    let mut c_index:Vec<usize> = Vec::new();
    let mut d_ret:Vec<i32> = Vec::new();
    let mut i:usize = 0;
    let mut j:usize = 0;
    let mut min_d:i32 = 0x6fffffff;

    if 0 == in_len {
        return Err("len is 0\n");
    }

    for e in in_chars {
        if e == c {
            c_index.push(i);
        }
        i += 1;
    }
    if 0 == c_index.len() {
        return Err("c_index is 0\n");
    }

    i = 0;
    while i < in_len {
        j = 0;
        while j < c_index.len() {
            let d = i32::abs((c_index[j] as i32) - (i as i32));
            min_d = i32::min(d, min_d);
            j += 1;
        }
        d_ret.push(min_d);
        min_d = 0x6fffffff;
        i += 1;
    }

    return Ok(d_ret);
}
carloscn commented 1 year ago

code

https://review.gerrithub.io/c/carloscn/structstudy/+/550179 https://github.com/carloscn/structstudy/commit/1b5197407063d10f1422777da12a381cded57ebb