-
题目链接:https://leetcode-cn.com/problems/shortest-distance-to-a-character/
-
思路:
- 用数组
target
记录目标字符的位置 - 答案数组进行初始化,方便记录最小值
- 遍历
target
,与ans
比较最小距离
- 用数组
-
代码:
class Solution { public: int abs(int i, int j){ return i > j ? i - j : j - i; } vector<int> shortestToChar(string s, char c) { vector<int> ans(s.length()); vector<int> target; for(int i = 0; i < s.length(); i++){ if(s[i] == c) target.push_back(i); ans[i] = 1e5; } for(int i = 0; i < target.size(); i++){ for(int j = 0; j < ans.size(); j++){ ans[j] = min(ans[j], abs(target[i], j)); } } return ans; } };
821字符串最小距离
最新推荐文章于 2024-08-22 15:48:46 发布