# 821. Shortest Distance to a Character

Given a string `S` and a character `C`, return an array of integers representing the shortest distance from the character `C` in the string.

Example 1:

``````Input: S = "loveleetcode", C = 'e'
Output: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]
``````

Note:

1. `S` string length is in `[1, 10000].`
2. `C` is a single character, and guaranteed to be in string `S`.
3. All letters in `S` and `C` are lowercase.

``````class Solution {
public:
vector<int> shortestToChar(string S, char C) {
int n = S.size();
vector<int> res(n, n);
for (int i = 0; i < n; ++i) {
if (S[i] == C) {res[i] = 0; continue;}
int j = i + 1;
while (j < n && S[j] != C) ++j;
if (j < n) res[i] = j - i;
j = i - 1;
while (j >= 0 && S[j] != C) --j;
if (j >= 0) res[i] = min(res[i], i - j);
}
return res;
}
};
``````

``````class Solution {
public:
vector<int> shortestToChar(string S, char C) {
vector<int> res, idx;
for (int i = 0; i < S.size(); ++i) {
if (S[i] == C) idx.push_back(i);
}
for (int i = 0; i < S.size(); ++i) {
auto it = lower_bound(idx.begin(), idx.end(), i);
if (it == idx.end()) res.push_back(i - *(--it));
else if (it == idx.begin()) res.push_back(*it - i);
else {
int d1 = *it - i, d2 = i - *(--it);
res.push_back(min(d1, d2));
}
}
return res;
}
};
``````

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

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

https://leetcode.com/problems/shortest-distance-to-a-character/

https://leetcode.com/problems/shortest-distance-to-a-character/discuss/125788/C%2B%2BJavaPython-2-Pass-with-Explanation

https://leetcode.com/problems/shortest-distance-to-a-character/discuss/156216/2-pass-solution-in-C%2B%2B-(beats-100-submissions).

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation