We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 76314a3 commit 9f18ab8Copy full SHA for 9f18ab8
Easy/821. Shortest Distance to a Character/solution.php
@@ -1,12 +1,40 @@
1
<?php
2
-class Solution {
3
-
+class Solution
+{
4
/**
5
* @param String $s
6
* @param String $c
7
* @return Integer[]
8
*/
9
- function shortestToChar($s, $c) {
10
+ public function shortestToChar($s, $c)
+ {
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
27
28
29
+ $result[$i] = min($result[$i], abs($pos - $i));
30
31
32
+ return $result;
33
}
-}
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]
AltStyle によって変換されたページ (->オリジナル) / アドレス: モード: デフォルト 音声ブラウザ ルビ付き 配色反転 文字拡大 モバイル
0 commit comments