0%

821. 字符的最短距离

821. 字符的最短距离

两次遍历
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
vector<int> shortestToChar(string s, char c) {
int prelocation = -1;
vector<int> ret(s.size(), INT_MAX);
for(int i = 0, sz = s.size(); i < sz; ++i)
{
if(s[i] == c)
prelocation = i;
if(prelocation >= 0)
ret[i] = min(ret[i], i - prelocation);
}
prelocation = -1;
for(int i = s.size() - 1; i >= 0; --i)
{
if(s[i] == c)
prelocation = i;
if(prelocation >= 0)
ret[i] = min(ret[i], prelocation - i);
}
return ret;
}
};