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 a0f7080

Browse files
feat: add typescript solution to lc problem: No.0821
No.0821.Shortest Distance to a Character
1 parent 6bc3a80 commit a0f7080

File tree

3 files changed

+55
-0
lines changed

3 files changed

+55
-0
lines changed

‎solution/0800-0899/0821.Shortest Distance to a Character/README.md‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,26 @@
6565

6666
```
6767

68+
### **TypeScript**
69+
70+
```ts
71+
function shortestToChar(s: string, c: string): number[] {
72+
const n = s.length;
73+
let ans = [];
74+
let pre = Infinity;
75+
for (let i = 0; i < n; i++) {
76+
if (s.charAt(i) == c) pre = i;
77+
ans[i] = Math.abs(pre - i);
78+
}
79+
pre = Infinity;
80+
for (let i = n - 1; i > -1; i--) {
81+
if (s.charAt(i) == c) pre = i;
82+
ans[i] = Math.min(Math.abs(pre - i), ans[i]);
83+
}
84+
return ans;
85+
};
86+
```
87+
6888
### **...**
6989

7090
```

‎solution/0800-0899/0821.Shortest Distance to a Character/README_EN.md‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,26 @@ The closest occurrence of &#39;e&#39; for index 8 is at index 6, so the distance
5454

5555
```
5656

57+
### **TypeScript**
58+
59+
```ts
60+
function shortestToChar(s: string, c: string): number[] {
61+
const n = s.length;
62+
let ans = [];
63+
let pre = Infinity;
64+
for (let i = 0; i < n; i++) {
65+
if (s.charAt(i) == c) pre = i;
66+
ans[i] = Math.abs(pre - i);
67+
}
68+
pre = Infinity;
69+
for (let i = n - 1; i > -1; i--) {
70+
if (s.charAt(i) == c) pre = i;
71+
ans[i] = Math.min(Math.abs(pre - i), ans[i]);
72+
}
73+
return ans;
74+
};
75+
```
76+
5777
### **...**
5878

5979
```
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
function shortestToChar(s: string, c: string): number[] {
2+
const n = s.length;
3+
let ans = [];
4+
let pre = Infinity;
5+
for (let i = 0; i < n; i++) {
6+
if (s.charAt(i) == c) pre = i;
7+
ans[i] = Math.abs(pre - i);
8+
}
9+
pre = Infinity;
10+
for (let i = n - 1; i > -1; i--) {
11+
if (s.charAt(i) == c) pre = i;
12+
ans[i] = Math.min(Math.abs(pre - i), ans[i]);
13+
}
14+
return ans;
15+
};

0 commit comments

Comments
(0)

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