Skip to content

Commit 624a9ae

Browse files
authored
Merge pull request #124 from NovaHe/feature/821
feature/821: add O(n) solution
2 parents 70aafb6 + 0c81766 commit 624a9ae

File tree

2 files changed

+48
-2
lines changed

2 files changed

+48
-2
lines changed

leetcode/0821.Shortest-Distance-to-a-Character/821. Shortest Distance to a Character.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,30 @@ import (
44
"math"
55
)
66

7+
// 解法一
78
func shortestToChar(s string, c byte) []int {
9+
n := len(s)
10+
res := make([]int, n)
11+
for i := range res {
12+
res[i] = n
13+
}
14+
for i := 0; i < n; i++ {
15+
if s[i] == c {
16+
res[i] = 0
17+
} else if i > 0 {
18+
res[i] = res[i-1] + 1
19+
}
20+
}
21+
for i := n - 1; i >= 0; i-- {
22+
if i < n-1 && res[i+1]+1 < res[i] {
23+
res[i] = res[i+1] + 1
24+
}
25+
}
26+
return res
27+
}
28+
29+
// 解法二
30+
func shortestToChar1(s string, c byte) []int {
831
res := make([]int, len(s))
932
for i := 0; i < len(s); i++ {
1033
if s[i] == c {

leetcode/0821.Shortest-Distance-to-a-Character/README.md

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
# [821. Shortest Distance to a Character](https://leetcode.com/problems/shortest-distance-to-a-character/)
22

3-
43
## 题目
54

65
Given a string `s` and a character `c` that occurs in `s`, return *an array of integers `answer` where* `answer.length == s.length` *and* `answer[i]` *is the shortest distance from* `s[i]` *to the character* `c` *in* `s`.
@@ -31,7 +30,8 @@ Output: [3,2,1,0]
3130

3231
## 解题思路
3332

34-
- 简单题。依次扫描字符串 S,针对每一个非字符 C 的字符,分别往左扫一次,往右扫一次,计算出距离目标字符 C 的距离,然后取左右两个距离的最小值存入最终答案数组中。
33+
- 解法一:从左至右更新一遍到C的值距离,再从右至左更新一遍到C的值,取两者中的最小值。
34+
- 解法二:依次扫描字符串 S,针对每一个非字符 C 的字符,分别往左扫一次,往右扫一次,计算出距离目标字符 C 的距离,然后取左右两个距离的最小值存入最终答案数组中。
3535

3636
## 代码
3737

@@ -42,7 +42,30 @@ import (
4242
"math"
4343
)
4444

45+
// 解法一
4546
func shortestToChar(s string, c byte) []int {
47+
n := len(s)
48+
res := make([]int, n)
49+
for i := range res {
50+
res[i] = n
51+
}
52+
for i := 0; i < n; i++ {
53+
if s[i] == c {
54+
res[i] = 0
55+
} else if i > 0 {
56+
res[i] = res[i-1] + 1
57+
}
58+
}
59+
for i := n - 1; i >= 0; i-- {
60+
if i < n-1 && res[i+1]+1 < res[i] {
61+
res[i] = res[i+1] + 1
62+
}
63+
}
64+
return res
65+
}
66+
67+
// 解法二
68+
func shortestToChar1(s string, c byte) []int {
4669
res := make([]int, len(s))
4770
for i := 0; i < len(s); i++ {
4871
if s[i] == c {

0 commit comments

Comments
 (0)