Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 9f18ab8

Browse files
committed
821
1 parent 76314a3 commit 9f18ab8

File tree

1 file changed

+33
-5
lines changed

1 file changed

+33
-5
lines changed
Lines changed: 33 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,40 @@
11
<?php
2-
class Solution {
3-
2+
class Solution
3+
{
44
/**
55
* @param String $s
66
* @param String $c
77
* @return Integer[]
88
*/
9-
function shortestToChar($s, $c) {
10-
9+
public function shortestToChar($s, $c)
10+
{
11+
$length = strlen($s);
12+
13+
$result = [];
14+
15+
$pos = -$length;
16+
for ($i = 0; $i < $length; $i++) {
17+
if ($s[$i] === $c) {
18+
$pos = $i;
19+
}
20+
$result[$i] = $i - $pos;
21+
}
22+
23+
$pos = 2 * $length;
24+
25+
for ($i = $length - 1; $i >= 0; $i--) {
26+
if ($s[$i] === $c) {
27+
$pos = $i;
28+
}
29+
$result[$i] = min($result[$i], abs($pos - $i));
30+
}
31+
32+
return $result;
1133
}
12-
}
34+
}
35+
36+
$solution = new Solution();
37+
$s = "loveleetcode";
38+
$c = "e";
39+
$output = $solution->shortestToChar($s, $c);
40+
print_r($output); // Output: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /