leetCode problem solution to find the shortest character path

1. Description of the topic

2. Analysis

  The simplest solution is to look to both sides for each character.

3. Code

  

 1 vector<int> shortestToChar(string S, char C) {
 2         
 3         vector<int> ans;
 4         for(size_t i = 0; i < S.size();i++)
 5         {
 6             if(S[i] == C)
 7                 ans.push_back(0);
 8             else
 9             {
10                 int j = i-1;
11                 while( j >= 0 && S[j] != C) j--;
12                 int k = i+1;
13                 while( k <= S.size()-1 && S[k] != C) k++;
14                 if( S[j] == C && S[k] == C)
15                 {
16                     ans.push_back( min(i-j,k-i) );
17                 }else if( S[j] == C && S[k] != C )
18                 {
19                     ans.push_back( i-j);
20                 }else{
21                     ans.push_back( k-i);
22                 }
 23                      
24                      
25              }
 26          }
 27          return years;
28          
29      }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324769782&siteId=291194637