1. Description of the topic
2. Analysis
The algorithm used before to find both sides of the big loop is O(n^2) complexity, and the complexity can be reduced by using multimap.
3. Code
1 vector< int > shortestToChar( string S, char C) { 2 // Use the multimap in the standard library to store each character and its subscript 3 // The advantage of multimap is that the key value can be repeated 4 vector< int > ans; 5 multimap< char , int > m; 6 for ( int i = 0 ; i< S.size(); i++ ) 7 m.insert( make_pair(S[i],i) ); 8 9 for ( int i = 0 ;i<S.size();i++) 10 { 11 if( S[i] == C ) 12 { 13 ans.push_back(0); 14 } 15 else 16 { 17 int k = S.size()-1; 18 for( auto pos = m.lower_bound( C ); pos != m.upper_bound( C ); pos++ ) 19 { 20 21 if( abs( pos->second - i ) < k ) 22 k = abs( pos->second -i ); 23 } 24 ans.push_back(k); 25 } 26 } 27 return ans; 28 }