Skip to content

Commit fe4737c

Browse files
Merge pull request youngyangyang04#1395 from fmtvar/offer-05
添加(剑指Offer05.替换空格.md):PHP版本
2 parents 3f538d4 + 3f0bb3c commit fe4737c

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

problems/剑指Offer05.替换空格.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -467,6 +467,42 @@ object Solution {
467467
def replaceSpace(s: String): String = {
468468
s.map(c => if(c == ' ') "%20" else c).mkString
469469
}
470+
}
471+
```
472+
473+
474+
PHP:
475+
```php
476+
function replaceSpace($s){
477+
$sLen = strlen($s);
478+
$moreLen = $this->spaceLen($s) * 2;
479+
480+
$head = $sLen - 1;
481+
$tail = $sLen + $moreLen - 1;
482+
483+
$s = $s . str_repeat(' ', $moreLen);
484+
while ($head != $tail) {
485+
if ($s[$head] == ' ') {
486+
$s[$tail--] = '0';
487+
$s[$tail--] = '2';
488+
$s[$tail] = '%';
489+
} else {
490+
$s[$tail] = $s[$head];
491+
}
492+
$head--;
493+
$tail--;
494+
}
495+
return $s;
496+
}
497+
// 统计空格个数
498+
function spaceLen($s){
499+
$count = 0;
500+
for ($i = 0; $i < strlen($s); $i++) {
501+
if ($s[$i] == ' ') {
502+
$count++;
503+
}
504+
}
505+
return $count;
470506
}
471507
```
472508

0 commit comments

Comments
 (0)