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 o...
Title Link
Title Analysis
thinking
Final code
D63 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.

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.

9 November 2019, 10:57 | Views: 2902

Add new comment

For adding a comment, please log in
or create account

0 comments