首页 > 其他 > 详细

821. Shortest Distance to a Character

时间:2018-06-15 23:53:25      阅读:308      评论:0      收藏:0      [点我收藏+]
 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

原文:https://www.cnblogs.com/zhuangbijingdeboke/p/9189307.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!