Skip to content

Commit 37805dd

Browse files
committed
Update reverse-string-ii solution
1 parent f110ede commit 37805dd

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

β€Žsrc/leetcode/ReverseStringII.phpβ€Ž

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,7 @@ public static function reverseStr(string $s, int $k): string
1212
return '';
1313
}
1414
$n = strlen($s);
15-
[$m, $n] = [0, strlen($s)];
16-
for (; $m < $n; $m += 2 * $k) {
15+
for ($m = 0; $m < $n; $m += 2 * $k) {
1716
for ($i = $m, $j = min($m + $k - 1, $n - 1); $i < $j; $i++, $j--) {
1817
$t = $s[$i];
1918
$s[$i] = $s[$j];
@@ -23,4 +22,26 @@ public static function reverseStr(string $s, int $k): string
2322

2423
return $s;
2524
}
25+
26+
public static function reverseStr2(string $s, int $k): string
27+
{
28+
if (empty($s) || $k <= 0) {
29+
return '';
30+
}
31+
[$i, $n] = [0, strlen($s)];
32+
while ($i < $n) {
33+
$j = min($i + $k - 1, $n - 1);
34+
$m = $j + $k + 1;
35+
while ($i < $j) {
36+
$t = $s[$i];
37+
$s[$i] = $s[$j];
38+
$s[$j] = $t;
39+
$i++;
40+
$j--;
41+
}
42+
$i = $m;
43+
}
44+
45+
return $s;
46+
}
2647
}

β€Žtests/leetcode/ReverseStringIITest.phpβ€Ž

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,4 +14,10 @@ public function testReverseStr(): void
1414
self::assertSame('bacdfeg', ReverseStringII::reverseStr('abcdefg', 2));
1515
self::assertSame('bacd', ReverseStringII::reverseStr('abcd', 2));
1616
}
17+
18+
public function testReverseStr2(): void
19+
{
20+
self::assertSame('bacdfeg', ReverseStringII::reverseStr2('abcdefg', 2));
21+
self::assertSame('bacd', ReverseStringII::reverseStr2('abcd', 2));
22+
}
1723
}

0 commit comments

Comments
Β (0)