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
.
Example 1:
Input: s = "loveleetcode", c = "e" Output: [3,2,1,0,1,0,0,1,2,2,1,0]
Example 2:
Input: s = "aaab", c = "b" Output: [3,2,1,0]
Constraints:
1 <= s.length <= 104
s[i]
andc
are lowercase English letters.c
occurs at least once ins
.
给定一个字符串 S 和一个字符 C。返回一个代表字符串 S 中每个字符到字符串 S 中的字符 C 的最短距离的数组。
- 解法一:从左至右更新一遍到 C 的值距离,再从右至左更新一遍到 C 的值,取两者中的最小值。
- 解法二:依次扫描字符串 S,针对每一个非字符 C 的字符,分别往左扫一次,往右扫一次,计算出距离目标字符 C 的距离,然后取左右两个距离的最小值存入最终答案数组中。
package leetcode import ( "math" ) // 解法一funcshortestToChar(sstring, cbyte) []int { n:=len(s) res:=make([]int, n) fori:=rangeres { res[i] =n } fori:=0; i<n; i++ { ifs[i] ==c { res[i] =0 } elseifi>0 { res[i] =res[i-1] +1 } } fori:=n-1; i>=0; i-- { ifi<n-1&&res[i+1]+1<res[i] { res[i] =res[i+1] +1 } } returnres } // 解法二funcshortestToChar1(sstring, cbyte) []int { res:=make([]int, len(s)) fori:=0; i<len(s); i++ { ifs[i] ==c { res[i] =0 } else { left, right:=math.MaxInt32, math.MaxInt32forj:=i+1; j<len(s); j++ { ifs[j] ==c { right=j-ibreak } } fork:=i-1; k>=0; k-- { ifs[k] ==c { left=i-kbreak } } res[i] =min(left, right) } } returnres } funcmin(a, bint) int { ifa>b { returnb } returna }