821. Shortest Distance to a Character Easy

@problem@discussion
#Array#Two Pointers#String



1/**
2 * [821] Shortest Distance to a Character
3 *
4 * 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.
5 * The distance between two indices i and j is abs(i - j), where abs is the absolute value function.
6 *  
7 * Example 1:
8 * 
9 * Input: s = "loveleetcode", c = "e"
10 * Output: [3,2,1,0,1,0,0,1,2,2,1,0]
11 * Explanation: The character 'e' appears at indices 3, 5, 6, and 11 (0-indexed).
12 * The closest occurrence of 'e' for index 0 is at index 3, so the distance is abs(0 - 3) = 3.
13 * The closest occurrence of 'e' for index 1 is at index 3, so the distance is abs(1 - 3) = 2.
14 * 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.
15 * The closest occurrence of 'e' for index 8 is at index 6, so the distance is abs(8 - 6) = 2.
16 * 
17 * Example 2:
18 * 
19 * Input: s = "aaab", c = "b"
20 * Output: [3,2,1,0]
21 * 
22 *  
23 * Constraints:
24 * 
25 * 	1 <= s.length <= 10^4
26 * 	s[i] and c are lowercase English letters.
27 * 	It is guaranteed that c occurs at least once in s.
28 * 
29 */
30pub struct Solution {}
31
32// problem: https://leetcode.com/problems/shortest-distance-to-a-character/
33// discuss: https://leetcode.com/problems/shortest-distance-to-a-character/discuss/?currentPage=1&orderBy=most_votes&query=
34
35// submission codes start here
36
37impl Solution {
38    pub fn shortest_to_char(s: String, c: char) -> Vec<i32> {
39        vec![]
40    }
41}
42
43// submission codes end
44
45#[cfg(test)]
46mod tests {
47    use super::*;
48
49    #[test]
50    fn test_821() {
51    }
52}
53


Back
© 2025 bowen.ge All Rights Reserved.