【Leetcode_easy】821. Shortest Distance to a Character

时间:2023-03-10 03:25:52
【Leetcode_easy】821. Shortest Distance to a Character

problem

821. Shortest Distance to a Character

solution1:

class Solution {
public:
vector<int> shortestToChar(string S, char C) {
int n = S.size();
vector<int> res(n, n);
for(int i=; i<n; ++i) if(S[i]==C) res[i] = ;
for(int i=; i<n; ++i) res[i] = min(res[i], abs(res[i-]+));
for(int i=n-; i>=; --i) res[i] = min(res[i], abs(res[i+]+));
return res;
}
};

solution2:

class Solution {
public:
vector<int> shortestToChar(string S, char C) {
int n = S.size();
vector<int> res(n, n);
int pos = -n;//errr...
for(int i=; i<n; ++i)
{
if(S[i]==C) pos = i;
res[i] = min(res[i], abs(i-pos));
}
for(int i=n-; i>=; --i)
{
if(S[i]==C) pos = i;
res[i] = min(res[i], abs(i-pos));
}
return res;
}
};

参考

1. Leetcode_easy_821. Shortest Distance to a Character;

2. Discuss;

3. grandyang;