ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

821. Shortest Distance to a Character

2021-10-20 15:35:14  阅读:151  来源: 互联网

标签:Distance distance index min Character abs Vec indexs 821


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
    }
}

 

标签:Distance,distance,index,min,Character,abs,Vec,indexs,821
来源: https://www.cnblogs.com/johnnyzhao/p/15429032.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有