feature/821: add O(n) solution

This commit is contained in:
novahe
2021-05-04 17:17:33 +08:00
parent 99fe55c7df
commit 0c817666f5
2 changed files with 48 additions and 2 deletions

View File

@ -4,7 +4,30 @@ import (
"math"
)
// 解法一
func shortestToChar(s string, c byte) []int {
n := len(s)
res := make([]int, n)
for i := range res {
res[i] = n
}
for i := 0; i < n; i++ {
if s[i] == c {
res[i] = 0
} else if i > 0 {
res[i] = res[i-1] + 1
}
}
for i := n - 1; i >= 0; i-- {
if i < n-1 && res[i+1]+1 < res[i] {
res[i] = res[i+1] + 1
}
}
return res
}
// 解法二
func shortestToChar1(s string, c byte) []int {
res := make([]int, len(s))
for i := 0; i < len(s); i++ {
if s[i] == c {

View File

@ -1,6 +1,5 @@
# [821. Shortest Distance to a Character](https://leetcode.com/problems/shortest-distance-to-a-character/)
## 题目
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]
## 解题思路
- 简单题。依次扫描字符串 S针对每一个非字符 C 的字符,分别往左扫一次,往右扫一次,计算出距离目标字符 C 的距离,然后取左右两个距离的最小值存入最终答案数组中
- 解法一从左至右更新一遍到C的值距离再从右至左更新一遍到C的值取两者中的最小值
- 解法二:依次扫描字符串 S针对每一个非字符 C 的字符,分别往左扫一次,往右扫一次,计算出距离目标字符 C 的距离,然后取左右两个距离的最小值存入最终答案数组中。
## 代码
@ -42,7 +42,30 @@ import (
"math"
)
// 解法一
func shortestToChar(s string, c byte) []int {
n := len(s)
res := make([]int, n)
for i := range res {
res[i] = n
}
for i := 0; i < n; i++ {
if s[i] == c {
res[i] = 0
} else if i > 0 {
res[i] = res[i-1] + 1
}
}
for i := n - 1; i >= 0; i-- {
if i < n-1 && res[i+1]+1 < res[i] {
res[i] = res[i+1] + 1
}
}
return res
}
// 解法二
func shortestToChar1(s string, c byte) []int {
res := make([]int, len(s))
for i := 0; i < len(s); i++ {
if s[i] == c {