821. Shortest Distance to a Character

时间:2023-03-10 06:33:50
821. Shortest Distance to a Character
 class Solution
{
public:
vector<int> shortestToChar(string S, char C)
{
int len=S.length();
vector<int>res(len,-); //as the result vector
vector<int> cindex; //save the index of C
for(int i=;i<len;i++) //write the distance of C and build the cindex
if(S[i]==C)
{
cindex.push_back(i);
res[i]=;
}
int szindex=cindex.size(); int count=;
for(int j=cindex[]-;j>=;j--) //write the distance before the first C
res[j]=count++; count=;
for(int k=cindex[szindex-]+;k<len;k++) //write the distance after the last C
res[k]=count++; for(int x=;x<szindex;x++) //write the distance between two C
{
count=;
int left=cindex[x-]+,right=cindex[x]-;
while(left<=right)
{
res[left++]=count;
res[right--]=count++;
}
}
return res;
}
};