码迷,mamicode.com
首页 > 其他好文 > 详细

821. Shortest Distance to a Character

时间:2018-06-16 00:05:21      阅读:307      评论:0      收藏:0      [点我收藏+]

标签:char   return   turn   cte   cin   for   public   ++   after   

 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

标签:char   return   turn   cte   cin   for   public   ++   after   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!