Time：2020-1-12

# D49 821. Shortest Distance to a Character

821. Shortest Distance to a Character

## Title Analysis

Given a string`s`And a character`c`

Returns the distance between each character in the string and the given character`c`The shortest distance.

## thinking

First find the characters with array key`C`In string`S`Location in.

If the current traversal position is the next character that appears`C`Before, you can directly subtract the subscript to get the distance.

Otherwise, when the current subscript is greater than the last occurrence character`C`And the next character exists`C`The distance is the smallest of the two.
When the distance is 0, mark the next to get`C`Location.

## Final code

``````<?php
class Solution {
function shortestToChar(\$S, \$C) {
\$S = str_split(\$S);
\$keys = array_keys(\$S,\$C);
\$distances = [];
\$prev = 0;
foreach(\$S as \$index => \$char){
\$dist = abs(\$keys[\$prev] - \$index);
if(\$index > \$keys[\$prev] && isset(\$keys[\$prev+1])){
\$dist = min(\$index-\$keys[\$prev],\$keys[\$prev+1]-\$index);
if(\$dist == 0){
\$prev++;
}
}
\$distances[] = \$dist;
}

return \$distances;
}
}``````