leetcode443. 压缩字符串

题目地址

https://leetcode.com/problems/string-compression

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
function compress(array $chars) :int {
$count = count($chars);
$index = 0;
$i = 0;

while ($i < $count) {
$currentChar = $chars[$i];
$n = 0;

while ($i < $count && $chars[$i] == $currentChar) {
$i++;
$n++;
}

$chars[$index++] = $currentChar;

if ($n == 1) {
continue;
}

$nStr = (string) $n;
$nLen = strlen($nStr);

for ($j = 0; $j < $nLen; $j++) {
$chars[$index++] = $nStr[$j];
}
}

return $index;
}