mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
Merge pull request #1395 from fmtvar/offer-05
添加(剑指Offer05.替换空格.md):PHP版本
This commit is contained in:
@ -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;
|
||||
}
|
||||
```
|
||||
|
||||
|
Reference in New Issue
Block a user