From 3665c051d794a3abc3b350c8cc5cdb897ef54f76 Mon Sep 17 00:00:00 2001 From: SevenMonths Date: Tue, 24 May 2022 16:53:39 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0(=E5=89=91=E6=8C=87Offer05.?= =?UTF-8?q?=E6=9B=BF=E6=8D=A2=E7=A9=BA=E6=A0=BC.md)=EF=BC=9Aphp=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/剑指Offer05.替换空格.md | 34 ++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/problems/剑指Offer05.替换空格.md b/problems/剑指Offer05.替换空格.md index 037bd427..63fb021a 100644 --- a/problems/剑指Offer05.替换空格.md +++ b/problems/剑指Offer05.替换空格.md @@ -415,6 +415,40 @@ func replaceSpace(_ s: String) -> String { +PHP: +```php +function replaceSpace($s){ + $sLen = strlen($s); + $moreLen = $this->spaceLen($s) * 2; + + $head = $sLen - 1; + $tail = $sLen + $moreLen - 1; + + $s = $s . str_repeat(' ', $moreLen); + while ($head != $tail) { + if ($s[$head] == ' ') { + $s[$tail--] = '0'; + $s[$tail--] = '2'; + $s[$tail] = '%'; + } else { + $s[$tail] = $s[$head]; + } + $head--; + $tail--; + } + return $s; +} +// 统计空格个数 +function spaceLen($s){ + $count = 0; + for ($i = 0; $i < strlen($s); $i++) { + if ($s[$i] == ' ') { + $count++; + } + } + return $count; +} +``` -----------------------