Title Link
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.
thinking
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
<?php 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; } else{ $others[$key] = $char; } } $keys = array_keys($chars); $chars = array_reverse($chars); $chars = array_combine($keys,$chars); $S = $chars+$others; ksort($S); return implode('',$S); } }If you think this article is useful to you, please use [love power generation] (https://afdian.net/@skys215) to help.