821. Shortest Distance to a Character

Posted zhuangbijingdeboke

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了821. Shortest Distance to a Character相关的知识,希望对你有一定的参考价值。

 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 };

 

以上是关于821. Shortest Distance to a Character的主要内容,如果未能解决你的问题,请参考以下文章

[Solution] 821. Shortest Distance to a Character

leetcode-821-Shortest Distance to a Character

821. Shortest Distance to a Character

[LeetCode&Python] Problem 821. Shortest Distance to a Character

LeetCode 821. Shortest Distance to a Character

(Easy) Shortest distance to Character LeetCode