【剑指Offer学习】【面试题4 : 替换空格】

题目:

请实现一个函数,把字符串中的每个空格替换成"%20",例如“We are happy.”,则输出“We%20are%20happy.”。

以下代码都是通过PHP代码实现。

拿到这个题目。我们第一反应就是使用内置php函数str_replace。

解法1:使用PHP内置函数

1 str_replace(" ","%20",$string);

解法2:从头遍历替换

算法:时间复杂度是O(n^2). 

我们不用php内置函数。然后自己通过php实现。则容易想到的是从头遍历字符串数组。然后遇到空格,就把后面的字符整体往后移动2格。把整体length加2.

如上图所示。我们逐次遍历。遇到空格。把wold 整体往后移动2格。然后替换%20. PHP代码实现如下。

 1 function strReplace($string){
 2     if(empty($string)) {
 3         return $string;
 4     }
 5     $length = strlen($string); //源字符串长度
 6     
 7     //遍历字符数组
 8     for ($i=0; $i < $length; $i++) { 
 9         if($string[$i] == ' ') {
10             //当前字符是空格。将后面的字符整体往后移动2格,从后往前移动。
11             for ($j=$length-1; $j > $i ; $j--) { 
12                 $string[$j+2] = $string[$j];
13             }
14             $string[$i] = '%';
15             $string[$i+1] = '2';
16             $string[$i+2] = '0';
17             //每次替换完,字符串长度加2。如果不加2 遍历到源字符串长度就是结束。目标字符串长度是大于源字符的。
18             $length = $length+2;
19         }
20     }
21     return $string;
22 
23 }

解法3:从后往前替换

算法时间复杂度:O(n)

我们可以尝试从后面往前替换。我们先算出最终字符串的长度。然后来从最终字符串的后面来比较。

大大减少了字符串数组移动的次数

PHP代码实现如下

 1 function strReplace($string){
 2     if(empty($string)) {
 3         return $string;
 4     }
 5     $length = strlen($string); //源字符串长度
 6     $spaceLenth = 0;//空格个数
 7     //获取空格的长度
 8     for ($i=0; $i < $length; $i++) { 
 9         if($string[$i] == ' ') {
10             $spaceLenth++;
11         }
12     }
13     if($spaceLenth == 0) {
14         return $string;
15     }
16     //目标字符串的长度。一个空格替换后,目标长度加2。N个空格,则增加2*N
17     $totalLen = 2*$spaceLenth+$length;
18     $length--;
19     $totalLen--;
20     while ($length >=0 && $length < $totalLen) {
21         if($string[$length] == ' '){
22             $string[$totalLen--] = '0';
23             $string[$totalLen--] = '2';
24             $string[$totalLen--] = '%';
25         }else{
26             //移动字符串
27             $string[$totalLen--] = $string[$length];
28         }
29         $length--;
30     }
31     return $string;
32 }

思考:

当我们在查找替换一个字符的时候。可以选择逆向替换。来减少移动的次数。

原文地址:https://www.cnblogs.com/tl542475736/p/8669273.html