标签:character lse etc rac 序列 ++ tput distance 距离
题意:给定一个小写字符串以及一个在小写字符串中的字母,字符串长度为[1, 10000]。返回字符串中每个字母离给定字母的最短距离序列。
举例:
Input: S = "loveleetcode", C = ‘e‘
Output: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]
分析:对于每个字母,分别预处理它左边和右边离其最近的给定字母的下标,最后取最小值即可。
class Solution {
public:
vector<int> shortestToChar(string S, char C) {
const int MAXN = 10000 + 10;
int left[MAXN], right[MAXN];
memset(left, -1, sizeof left);
memset(right, -1, sizeof right);
int len = S.size();
int tmp = -1;
for(int i = 0; i < len; ++i){
if(S[i] == C) tmp = i;
left[i] = tmp;
}
tmp = -1;
for(int i = len - 1; i >= 0; --i){
if(S[i] == C) tmp = i;
right[i] = tmp;
}
vector<int> ans;
for(int i = 0; i < len; ++i){
int tmpl, tmpr;
if(left[i] != -1) tmpl = i - left[i];
else tmpl = len;
if(right[i] != -1) tmpr = right[i] - i;
else tmpr = len;
ans.push_back(min(tmpl, tmpr));
}
return ans;
}
};
LeetCode 821. Shortest Distance to a Character
标签:character lse etc rac 序列 ++ tput distance 距离
原文地址:https://www.cnblogs.com/tyty-Somnuspoppy/p/9396292.html