Leetcode PHP problem solving — d49 821. Short distance to a character


D49 821. Shortest Distance to a Character

Title Link

821. Shortest Distance to a Character

Title Analysis

Given a stringsAnd a characterc

Returns the distance between each character in the string and the given charactercThe shortest distance.


First find the characters with array keyCIn stringSLocation in.

If the current traversal position is the next character that appearsCBefore, you can directly subtract the subscript to get the distance.

Otherwise, when the current subscript is greater than the last occurrence characterCAnd the next character existsCThe distance is the smallest of the two.
When the distance is 0, mark the next to getCLocation.

Final code

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){
            $distances[] = $dist;

        return $distances;

If you think this article is useful to you, you are welcome to use AI power generation support.