Leetcode PHP solution -- D63 917. Reverse Only Letters

D63 917. Reverse Only Letters

Title Link

917. Reverse Only Letters

Title Analysis

Given a string containing symbols, it only reverses the occurrence order of the letters, and does not change the occurrence position of the symbols.


First, the string is divided into two parts: letter and symbol, and the subscript is reserved.
Extract the key and value of the alphabet array, reverse the value part, and merge it into the key array.
Then overwrite the corresponding key in the original array.

Final code

class Solution {

         * @param String $S
              * @return String
                       function reverseOnlyLetters($S) {
                               $S = str_split($S);
                                       $chars = [];
                                               $others = [];
                                                       foreach($S as $key=>$char){
                                                                   if(($char>='a' && $char<='z')
                                                                                 || ($char>='A' && $char<='Z')
                                                                                                             $chars[$key] = $char;
                                                                                                                                                     $others[$key] = $char;
                                                                                                                                                                                 $keys = array_keys($chars);
                                                                                                                                                                                         $chars = array_reverse($chars);
                                                                                                                                                                                                 $chars = array_combine($keys,$chars);
                                                                                                                                                                                                         $S = $chars+$others;
                                                                                                                                                                                                                         return implode('',$S);
                                                                                                                                                                                                                         If you think this article is useful to you, please use [love power generation] (https://afdian.net/@skys215) to help.

Tags: PHP

Posted on Sat, 09 Nov 2019 10:57:46 -0500 by phpmixx