-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathReverseStringII.php
More file actions
47 lines (41 loc) · 1 KB
/
ReverseStringII.php
File metadata and controls
47 lines (41 loc) · 1 KB
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<?php
declare(strict_types=1);
namespace leetcode;
class ReverseStringII
{
public static function reverseStr(string $s, int $k): string
{
if (empty($s) || $k <= 0) {
return '';
}
$n = strlen($s);
for ($m = 0; $m < $n; $m += 2 * $k) {
for ($i = $m, $j = min($m + $k - 1, $n - 1); $i < $j; $i++, $j--) {
$t = $s[$i];
$s[$i] = $s[$j];
$s[$j] = $t;
}
}
return $s;
}
public static function reverseStr2(string $s, int $k): string
{
if (empty($s) || $k <= 0) {
return '';
}
[$i, $n] = [0, strlen($s)];
while ($i < $n) {
$j = min($i + $k - 1, $n - 1);
$m = $j + $k + 1;
while ($i < $j) {
$t = $s[$i];
$s[$i] = $s[$j];
$s[$j] = $t;
$i++;
$j--;
}
$i = $m;
}
return $s;
}
}