题目描述
给定一个字符串 S 和一个字符 C。返回一个代表字符串 S 中每个字符到字符串 S 中的字符 C 的最短距离的数组。
输入: S = “loveleetcode”, C = ‘e’
输出: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shortest-distance-to-a-character
思路
1、类似双指针,先找到第一个相遇位置的下表,
2、开始比较,计算两个之间的距离取小值
class Solution {
public:
int findC(string s, char c, int start) {
int i=0;
for(i = start; i < s.length(); i++) {
if(s[i] == c) {
return i;
}
}
return 100000;
}
vector<int> shortestToChar(string S, char C) {
int left = -10001;
// 找到第一个
int right = findC(S, C, 0);
vector<int> res;
for(int i = 0; i < S.length(); i++) {
if(S[i] == C) {
left = i;
res.push_back(0);
right = findC(S, C, i+1);
} else {
res.push_back(std::min(i-left, right-i));
}
}
return res;
}
};
复杂度分析
时间复杂度o(n)
空间复杂度o(n)