mirror of
https://github.com/halfrost/LeetCode-Go.git
synced 2025-07-06 09:23:19 +08:00
Merge pull request #124 from NovaHe/feature/821
feature/821: add O(n) solution
This commit is contained in:
@ -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 {
|
||||
|
@ -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 {
|
||||
|
Reference in New Issue
Block a user