Merge pull request #1395 from fmtvar/offer-05

添加(剑指Offer05.替换空格.md):PHP版本
This commit is contained in:
程序员Carl
2022-06-25 12:12:52 +08:00
committed by GitHub

View File

@ -467,6 +467,42 @@ object Solution {
def replaceSpace(s: String): String = {
s.map(c => if(c == ' ') "%20" else c).mkString
}
}
```
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;
}
```