821.字符的最短距离
class Solution {
public:
vector<int> shortestToChar(string S, char C) {
vector<int> res, C_pos;
int pos_i = 1, temp;
int N = S.length();
for (int i = 0; i < N; i++) {
if (S[i] == C) {
C_pos.push_back(i);
}
}
for (int i = 0; i < N; i++) {
if (C_pos.size() == 1) {
res.push_back(abs(C_pos[0] - i));
continue;
}
if (i <= C_pos[0] && C_pos.size() > 1) {
res.push_back(C_pos[0] - i);
}
else {
temp = min(abs(i - C_pos[pos_i - 1]), abs(C_pos[pos_i] - i));
res.push_back(temp);
if (temp == 0 && pos_i < C_pos.size()-1) {
pos_i++;
}
}
}
return res;
}
};
int main()
{
Solution sol;
string S = "abba";
char C = 'b';
int N = sol.shortestToChar(S, C).size();
for (int i = 0; i < N; i++) {
cout << sol.shortestToChar(S, C)[i] << ',';
}
cout << endl;
return 0;
}