821. Shortest Distance to a Character

use std::cmp::min;

/**
821. Shortest Distance to a Character
https://leetcode.com/problems/shortest-distance-to-a-character/
Given a string s and a character c that occurs in s,
return an array of integers answer where answer.length == s.length and answer[i] is the distance from index i to the closest occurrence of character c in s.
The distance between two indices i and j is abs(i - j), where abs is the absolute value function.

Example 1:
Input: s = "loveleetcode", c = "e"
Output: [3,2,1,0,1,0,0,1,2,2,1,0]
Explanation: The character 'e' appears at indices 3, 5, 6, and 11 (0-indexed).
The closest occurrence of 'e' for index 0 is at index 3, so the distance is abs(0 - 3) = 3.
The closest occurrence of 'e' for index 1 is at index 3, so the distance is abs(1 - 3) = 2.
For index 4, there is a tie between the 'e' at index 3 and the 'e' at index 5, but the distance is still the same: abs(4 - 3) == abs(4 - 5) = 1.
The closest occurrence of 'e' for index 8 is at index 6, so the distance is abs(8 - 6) = 2.

Example 2:
Input: s = "aaab", c = "b"
Output: [3,2,1,0]

Constraints:
1. 1 <= s.length <= 104
2. s[i] and c are lowercase English letters.
3. It is guaranteed that c occurs at least once in s.
*/

/*
Solution:find out all the index of c and char of s, compare those two index and find out the shortest one;
Time:O(n^2), Space:O(n);
*/

pub struct Solution {}

struct Index {
    c: char,
    index: i32,
}

impl Solution {
    pub fn shortest_to_char(s: String, c: char) -> Vec<i32> {
        let size = s.len();
        let mut indexs: Vec<Index> = Vec::new();
        let mut indexs_c: Vec<i32> = Vec::new();
        let mut result = Vec::with_capacity(size);
        for (i,ch) in s.char_indices() {
            indexs.push(Index { c: ch, index: i as i32 });
            if (ch == c) {
                indexs_c.push(i as i32);
            }
        }
        for item in indexs.iter() {
            let mut min_value = std::i32::MAX;
            for i2 in indexs_c.iter()  {
                min_value = std::cmp::min(min_value, (i2 - item.index).abs());
            }
            result.push(min_value);
        }
        result
    }
}

 

上一篇:MATLAB 计算点到直线的距离


下一篇:Acwing--多重背包问题 II(二进制+01背包优化)