1 class Solution 2 { 3 public: 4 vector<int> shortestToChar(string S, char C) 5 { 6 int len=S.length(); 7 vector<int>res(len,-1); //as the result vector 8 vector<int> cindex; //save the index of C 9 for(int i=0;i<len;i++) //write the distance of C and build the cindex 10 if(S[i]==C) 11 { 12 cindex.push_back(i); 13 res[i]=0; 14 } 15 int szindex=cindex.size(); 16 17 int count=1; 18 for(int j=cindex[0]-1;j>=0;j--) //write the distance before the first C 19 res[j]=count++; 20 21 count=1; 22 for(int k=cindex[szindex-1]+1;k<len;k++) //write the distance after the last C 23 res[k]=count++; 24 25 for(int x=1;x<szindex;x++) //write the distance between two C 26 { 27 count=1; 28 int left=cindex[x-1]+1,right=cindex[x]-1; 29 while(left<=right) 30 { 31 res[left++]=count; 32 res[right--]=count++; 33 } 34 } 35 return res; 36 } 37 };
原文地址:https://www.cnblogs.com/zhuangbijingdeboke/p/9189307.html
时间: 2024-11-08 19:08:45