zoukankan      html  css  js  c++  java
  • 空格替换

    描述

    设计一种方法,将一个字符串中的所有空格替换成 %20 。你可以假设该字符串有足够的空间来加入新的字符,且你得到的是“真实的”字符长度。

    你的程序还需要返回被替换后的字符串的长度。

    样例

    对于字符串"Mr John Smith", 长度为 13

    替换空格之后,参数中的字符串需要变为"Mr%20John%20Smith",并且把新长度 17 作为结果返回。

    挑战

    在原字符串(字符数组)中完成替换,不适用额外空间

     1 <?php
     2 
     3 /**
     4  * 方法一 由于php数组特殊的数据结构导致处理起来比较方便
     5  */
     6 function solution1($str)
     7 {
     8     $len = strlen($str);
     9     $new_str = '';
    10     for($i=0; $i<$len; $i++)
    11     {
    12         if($str[$i] != ' ')
    13         {
    14             $new_str .= $str[$i];
    15         } else {
    16             $new_str .= '%20';
    17         }
    18     }
    19     return $new_str;
    20 }
    21 
    22 $str = solution1('Mr John Smith');
    23 echo $str . '----------' . strlen($str);
    24 
    25 /**
    26  * 方法二 强类型语言的处理方式
    27  * 1.先确定有多少个空格
    28  * 2.非空格字符往后移,空格字符用%20填充
    29  */
    30 function solution2($arr)
    31 {
    32     $len = count($arr);
    33     $count = 0;//记录有多少个空格
    34     for($i=0; $i<$len; $i++)
    35     {
    36         if($arr[$i] == ' ')
    37         {
    38             $count++;
    39         }
    40     }
    41     if(0 == $count)
    42     {
    43         return $arr;//字符串数组中没有空格
    44     }
    45     for($i=$len-1;$i>0;$i--)
    46     {
    47         if($arr[$i] != ' ')
    48         {
    49             $index = $i + $count * 2;
    50             $arr[$index] = $arr[$i];
    51         } else {
    52             $count--;
    53             $arr[$i + $count * 2] = '%';
    54             $arr[$i + $count * 2 + 1] = '2';
    55             $arr[$i  + $count * 2 + 2] = '0';
    56         }
    57     }
    58     return $arr;
    59 }
    60 $arr = ['M','r',' ', 'J','o','h','n',' ','S','m','i','t','h'];
    61 $str = solution2($arr);
    62 echo "<pre>";print_r($str) . '----------' . count($str);
  • 相关阅读:
    P4297 [NOI2006]网络收费
    P4207 [NOI2005]月下柠檬树
    bzoj2517 矩形覆盖
    bzoj2506 calc
    ......
    SP1811 LCS
    CF585E Present for Vitalik the Philatelist
    好康的
    CF605E Intergalaxy Trips
    字符串
  • 原文地址:https://www.cnblogs.com/573583868wuy/p/9286517.html
Copyright © 2011-2022 走看看